Skip to content

Commit

Permalink
errors: factor out "of type" text generation
Browse files Browse the repository at this point in the history
Also slightly revise the grammar of two-expected value scenario.
  • Loading branch information
TimothyGu committed Apr 25, 2017
1 parent 061c5da commit c02820a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
27 changes: 17 additions & 10 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
2 changes: 1 addition & 1 deletion test/parallel/test-internal-errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit c02820a

Please sign in to comment.