Skip to content

Commit 33c5dbe

Browse files
committed
errors: improve ERR_INVALID_ARG_TYPE
ERR_INVALID_ARG_TYPE is the most common error used throughout the code base. This improves the error message by providing more details to the user and by indicating more precisely which values are allowed ones and which ones are not. It adds the actual input to the error message in case it's a primitive. If it's a class instance, it'll print the class name instead of "object" and "falsy" or similar entries are not named "type" anymore. PR-URL: #29675 Reviewed-By: Rich Trott <[email protected]>
1 parent 4df3652 commit 33c5dbe

File tree

127 files changed

+664
-533
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

127 files changed

+664
-533
lines changed

lib/internal/errors.js

+123-33
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,21 @@ const {
2323
const messages = new Map();
2424
const codes = {};
2525

26+
const classRegExp = /^([A-Z][a-z0-9]*)+$/;
27+
// Sorted by a rough estimate on most frequently used entries.
28+
const kTypes = [
29+
'string',
30+
'function',
31+
'number',
32+
'object',
33+
// Accept 'Function' and 'Object' as alternative to the lower cased version.
34+
'Function',
35+
'Object',
36+
'boolean',
37+
'bigint',
38+
'symbol'
39+
];
40+
2641
const { kMaxLength } = internalBinding('buffer');
2742

2843
const MainContextError = Error;
@@ -610,26 +625,6 @@ function isStackOverflowError(err) {
610625
err.message === maxStack_ErrorMessage;
611626
}
612627

613-
function oneOf(expected, thing) {
614-
assert(typeof thing === 'string', '`thing` has to be of type string');
615-
if (ArrayIsArray(expected)) {
616-
const len = expected.length;
617-
assert(len > 0,
618-
'At least one expected value needs to be specified');
619-
expected = expected.map((i) => String(i));
620-
if (len > 2) {
621-
return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
622-
expected[len - 1];
623-
} else if (len === 2) {
624-
return `one of ${thing} ${expected[0]} or ${expected[1]}`;
625-
} else {
626-
return `of ${thing} ${expected[0]}`;
627-
}
628-
} else {
629-
return `of ${thing} ${String(expected)}`;
630-
}
631-
}
632-
633628
// Only use this for integers! Decimal numbers do not work with this function.
634629
function addNumericalSeparator(val) {
635630
let res = '';
@@ -926,27 +921,114 @@ E('ERR_INVALID_ADDRESS_FAMILY', function(addressType, host, port) {
926921
E('ERR_INVALID_ARG_TYPE',
927922
(name, expected, actual) => {
928923
assert(typeof name === 'string', "'name' must be a string");
924+
if (!ArrayIsArray(expected)) {
925+
expected = [expected];
926+
}
927+
928+
let msg = 'The ';
929+
if (name.endsWith(' argument')) {
930+
// For cases like 'first argument'
931+
msg += `${name} `;
932+
} else {
933+
const type = name.includes('.') ? 'property' : 'argument';
934+
msg += `"${name}" ${type} `;
935+
}
929936

930937
// determiner: 'must be' or 'must not be'
931-
let determiner;
932938
if (typeof expected === 'string' && expected.startsWith('not ')) {
933-
determiner = 'must not be';
939+
msg += 'must not be ';
934940
expected = expected.replace(/^not /, '');
935941
} else {
936-
determiner = 'must be';
942+
msg += 'must be ';
937943
}
938944

939-
let msg;
940-
if (name.endsWith(' argument')) {
941-
// For cases like 'first argument'
942-
msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
943-
} else {
944-
const type = name.includes('.') ? 'property' : 'argument';
945-
msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
945+
const types = [];
946+
const instances = [];
947+
const other = [];
948+
949+
for (const value of expected) {
950+
assert(typeof value === 'string',
951+
'All expected entries have to be of type string');
952+
if (kTypes.includes(value)) {
953+
types.push(value.toLowerCase());
954+
} else if (classRegExp.test(value)) {
955+
instances.push(value);
956+
} else {
957+
assert(value !== 'object',
958+
'The value "object" should be written as "Object"');
959+
other.push(value);
960+
}
946961
}
947962

948-
// TODO(BridgeAR): Improve the output by showing `null` and similar.
949-
msg += `. Received type ${typeof actual}`;
963+
// Special handle `object` in case other instances are allowed to outline
964+
// the differences between each other.
965+
if (instances.length > 0) {
966+
const pos = types.indexOf('object');
967+
if (pos !== -1) {
968+
types.splice(pos, 1);
969+
instances.push('Object');
970+
}
971+
}
972+
973+
if (types.length > 0) {
974+
if (types.length > 2) {
975+
const last = types.pop();
976+
msg += `one of type ${types.join(', ')}, or ${last}`;
977+
} else if (types.length === 2) {
978+
msg += `one of type ${types[0]} or ${types[1]}`;
979+
} else {
980+
msg += `of type ${types[0]}`;
981+
}
982+
if (instances.length > 0 || other.length > 0)
983+
msg += ' or ';
984+
}
985+
986+
if (instances.length > 0) {
987+
if (instances.length > 2) {
988+
const last = instances.pop();
989+
msg += `an instance of ${instances.join(', ')}, or ${last}`;
990+
} else {
991+
msg += `an instance of ${instances[0]}`;
992+
if (instances.length === 2) {
993+
msg += ` or ${instances[1]}`;
994+
}
995+
}
996+
if (other.length > 0)
997+
msg += ' or ';
998+
}
999+
1000+
if (other.length > 0) {
1001+
if (other.length > 2) {
1002+
const last = other.pop();
1003+
msg += `one of ${other.join(', ')}, or ${last}`;
1004+
} else if (other.length === 2) {
1005+
msg += `one of ${other[0]} or ${other[1]}`;
1006+
} else {
1007+
if (other[0].toLowerCase() !== other[0])
1008+
msg += 'an ';
1009+
msg += `${other[0]}`;
1010+
}
1011+
}
1012+
1013+
if (actual == null) {
1014+
msg += `. Received ${actual}`;
1015+
} else if (typeof actual === 'function' && actual.name) {
1016+
msg += `. Received function ${actual.name}`;
1017+
} else if (typeof actual === 'object') {
1018+
if (actual.constructor && actual.constructor.name) {
1019+
msg += `. Received an instance of ${actual.constructor.name}`;
1020+
} else {
1021+
const inspected = lazyInternalUtilInspect()
1022+
.inspect(actual, { depth: -1 });
1023+
msg += `. Received ${inspected}`;
1024+
}
1025+
} else {
1026+
let inspected = lazyInternalUtilInspect()
1027+
.inspect(actual, { colors: false });
1028+
if (inspected.length > 25)
1029+
inspected = `${inspected.slice(0, 25)}...`;
1030+
msg += `. Received type ${typeof actual} (${inspected})`;
1031+
}
9501032
return msg;
9511033
}, TypeError);
9521034
E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
@@ -1034,7 +1116,15 @@ E('ERR_INVALID_URL', function(input) {
10341116
return `Invalid URL: ${input}`;
10351117
}, TypeError);
10361118
E('ERR_INVALID_URL_SCHEME',
1037-
(expected) => `The URL must be ${oneOf(expected, 'scheme')}`, TypeError);
1119+
(expected) => {
1120+
if (typeof expected === 'string')
1121+
expected = [expected];
1122+
assert(expected.length <= 2);
1123+
const res = expected.length === 2 ?
1124+
`one of scheme ${expected[0]} or ${expected[1]}` :
1125+
`of scheme ${expected[0]}`;
1126+
return `The URL must be ${res}`;
1127+
}, TypeError);
10381128
E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error);
10391129
E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error);
10401130
E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error);

test/common/index.js

+21
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,26 @@ function runWithInvalidFD(func) {
718718
printSkipMessage('Could not generate an invalid fd');
719719
}
720720

721+
// A helper function to simplify checking for ERR_INVALID_ARG_TYPE output.
722+
function invalidArgTypeHelper(input) {
723+
if (input == null) {
724+
return ` Received ${input}`;
725+
}
726+
if (typeof input === 'function' && input.name) {
727+
return ` Received function ${input.name}`;
728+
}
729+
if (typeof input === 'object') {
730+
if (input.constructor && input.constructor.name) {
731+
return ` Received an instance of ${input.constructor.name}`;
732+
}
733+
return ` Received ${util.inspect(input, { depth: -1 })}`;
734+
}
735+
let inspected = util.inspect(input, { colors: false });
736+
if (inspected.length > 25)
737+
inspected = `${inspected.slice(0, 25)}...`;
738+
return ` Received type ${typeof input} (${inspected})`;
739+
}
740+
721741
module.exports = {
722742
allowGlobals,
723743
buildType,
@@ -735,6 +755,7 @@ module.exports = {
735755
hasIntl,
736756
hasCrypto,
737757
hasMultiLocalhost,
758+
invalidArgTypeHelper,
738759
isAIX,
739760
isAlive,
740761
isFreeBSD,

test/es-module/test-esm-loader-modulemap.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ common.expectsError(
2525
{
2626
code: 'ERR_INVALID_ARG_TYPE',
2727
type: TypeError,
28-
message: 'The "url" argument must be of type string. Received type number'
28+
message: 'The "url" argument must be of type string. Received type number' +
29+
' (1)'
2930
}
3031
);
3132

@@ -34,7 +35,8 @@ common.expectsError(
3435
{
3536
code: 'ERR_INVALID_ARG_TYPE',
3637
type: TypeError,
37-
message: 'The "url" argument must be of type string. Received type number'
38+
message: 'The "url" argument must be of type string. Received type number' +
39+
' (1)'
3840
}
3941
);
4042

@@ -43,8 +45,8 @@ common.expectsError(
4345
{
4446
code: 'ERR_INVALID_ARG_TYPE',
4547
type: TypeError,
46-
message: 'The "job" argument must be of type ModuleJob. ' +
47-
'Received type string'
48+
message: 'The "job" argument must be an instance of ModuleJob. ' +
49+
"Received type string ('notamodulejob')"
4850
}
4951
);
5052

@@ -53,6 +55,7 @@ common.expectsError(
5355
{
5456
code: 'ERR_INVALID_ARG_TYPE',
5557
type: TypeError,
56-
message: 'The "url" argument must be of type string. Received type number'
58+
message: 'The "url" argument must be of type string. Received type number' +
59+
' (1)'
5760
}
5861
);

test/internet/test-dns-promises-resolve.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ const dnsPromises = require('dns').promises;
2626
code: 'ERR_INVALID_ARG_TYPE',
2727
type: TypeError,
2828
message: 'The "rrtype" argument must be of type string. ' +
29-
`Received type ${typeof rrtype}`
29+
`Received type ${typeof rrtype} (${rrtype})`
3030
}
3131
);
3232
}

test/parallel/test-assert-async.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,8 @@ promises.push(assert.rejects(
125125
assert.rejects('fail', {}),
126126
{
127127
code: 'ERR_INVALID_ARG_TYPE',
128-
message: 'The "promiseFn" argument must be one of type ' +
129-
'Function or Promise. Received type string'
128+
message: 'The "promiseFn" argument must be of type function or an ' +
129+
"instance of Promise. Received type string ('fail')"
130130
}
131131
));
132132

@@ -225,8 +225,8 @@ promises.push(assert.rejects(
225225
assert.doesNotReject(123),
226226
{
227227
code: 'ERR_INVALID_ARG_TYPE',
228-
message: 'The "promiseFn" argument must be one of type ' +
229-
'Function or Promise. Received type number'
228+
message: 'The "promiseFn" argument must be of type ' +
229+
'function or an instance of Promise. Received type number (123)'
230230
}
231231
));
232232
/* eslint-enable no-restricted-syntax */

test/parallel/test-assert.js

+12-10
Original file line numberDiff line numberDiff line change
@@ -414,8 +414,8 @@ assert.throws(
414414
{
415415
code: 'ERR_INVALID_ARG_TYPE',
416416
type: TypeError,
417-
message: 'The "fn" argument must be of type Function. Received ' +
418-
`type ${typeof fn}`
417+
message: 'The "fn" argument must be of type function.' +
418+
common.invalidArgTypeHelper(fn)
419419
}
420420
);
421421
};
@@ -484,8 +484,8 @@ assert.throws(() => {
484484
{
485485
code: 'ERR_INVALID_ARG_TYPE',
486486
name: 'TypeError',
487-
message: 'The "options" argument must be of type Object. ' +
488-
`Received type ${typeof input}`
487+
message: 'The "options" argument must be of type object.' +
488+
common.invalidArgTypeHelper(input)
489489
});
490490
});
491491
}
@@ -931,8 +931,9 @@ common.expectsError(
931931
{
932932
code: 'ERR_INVALID_ARG_TYPE',
933933
type: TypeError,
934-
message: 'The "error" argument must be one of type Object, Error, ' +
935-
'Function, or RegExp. Received type string'
934+
message: 'The "error" argument must be of type function or ' +
935+
'an instance of Error, RegExp, or Object. Received type string ' +
936+
"('Error message')"
936937
}
937938
);
938939

@@ -945,8 +946,9 @@ common.expectsError(
945946
() => assert.throws(() => {}, input),
946947
{
947948
code: 'ERR_INVALID_ARG_TYPE',
948-
message: 'The "error" argument must be one of type Object, Error, ' +
949-
`Function, or RegExp. Received type ${typeof input}`
949+
message: 'The "error" argument must be of type function or ' +
950+
'an instance of Error, RegExp, or Object.' +
951+
common.invalidArgTypeHelper(input)
950952
}
951953
);
952954
});
@@ -1024,8 +1026,8 @@ common.expectsError(
10241026
{
10251027
type: TypeError,
10261028
code: 'ERR_INVALID_ARG_TYPE',
1027-
message: 'The "expected" argument must be one of type Function or ' +
1028-
'RegExp. Received type object'
1029+
message: 'The "expected" argument must be of type function or an ' +
1030+
'instance of RegExp. Received an instance of Object'
10291031
}
10301032
);
10311033

test/parallel/test-buffer-alloc.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -967,19 +967,19 @@ common.expectsError(
967967
{
968968
code: 'ERR_INVALID_ARG_TYPE',
969969
type: TypeError,
970-
message: 'The "target" argument must be one of type Buffer or Uint8Array.' +
971-
' Received type undefined'
970+
message: 'The "target" argument must be an instance of Buffer or ' +
971+
'Uint8Array. Received undefined'
972972
});
973973

974974
assert.throws(() => Buffer.from(), {
975975
name: 'TypeError',
976-
message: 'The first argument must be one of type string, Buffer, ' +
977-
'ArrayBuffer, Array, or Array-like Object. Received type undefined'
976+
message: 'The first argument must be of type string or an instance of ' +
977+
'Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined'
978978
});
979979
assert.throws(() => Buffer.from(null), {
980980
name: 'TypeError',
981-
message: 'The first argument must be one of type string, Buffer, ' +
982-
'ArrayBuffer, Array, or Array-like Object. Received type object'
981+
message: 'The first argument must be of type string or an instance of ' +
982+
'Buffer, ArrayBuffer, or Array or an Array-like Object. Received null'
983983
});
984984

985985
// Test prototype getters don't throw

test/parallel/test-buffer-arraybuffer.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ assert.throws(function() {
4343
}, {
4444
code: 'ERR_INVALID_ARG_TYPE',
4545
name: 'TypeError',
46-
message: 'The first argument must be one of type string, Buffer,' +
47-
' ArrayBuffer, Array, or Array-like Object. Received type object'
46+
message: 'The first argument must be of type string or an instance of ' +
47+
'Buffer, ArrayBuffer, or Array or an Array-like Object. Received ' +
48+
'an instance of AB'
4849
});
4950

5051
// Test the byteOffset and length arguments

0 commit comments

Comments
 (0)