diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 58cc4979392b57..a124a5f65d5738 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -91,22 +91,29 @@ E('ERR_UNKNOWN_BUILTIN_MODULE', (id) => `No such built-in module: ${id}`); function invalidArgType(name, expected, actual) { assert(name, 'name is required'); + var msg = `The "${name}" argument must be ${oneOf(expected, 'type')}`; + if (arguments.length >= 3) { + msg += `. Received type ${actual !== null ? typeof actual : 'null'}`; + } + return msg; +} + +function oneOf(expected, thing) { assert(expected, 'expected is required'); - var msg = `The "${name}" argument must be `; + assert(typeof thing === 'string', 'thing is required'); if (Array.isArray(expected)) { - var len = expected.length; + const len = expected.length; + assert(len > 0, 'At least one expected value needs to be specified'); expected = expected.map((i) => String(i)); - if (len > 1) { - msg += `one of type ${expected.slice(0, len - 1).join(', ')}, or ` + + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { - msg += `of type ${expected[0]}`; + return `of ${thing} ${expected[0]}`; } } else { - msg += `of type ${String(expected)}`; + return `of ${thing} ${String(expected)}`; } - if (arguments.length >= 3) { - msg += `. Received type ${actual !== null ? typeof actual : 'null'}`; - } - return msg; } diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index fbd627b0301dfd..a673fdf8a4caf4 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -137,7 +137,7 @@ assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', 'b']), assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', ['b']]), 'The "a" argument must be of type b'); assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', ['b', 'c']]), - 'The "a" argument must be one of type b, or c'); + 'The "a" argument must be one of type b or c'); assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', ['b', 'c', 'd']]), 'The "a" argument must be one of type b, c, or d');