Skip to content

Commit

Permalink
errors: extract type detection & use in ERR_INVALID_RETURN_VALUE
Browse files Browse the repository at this point in the history
  • Loading branch information
JakobJingleheimer committed Jun 24, 2022
1 parent 3507b3f commit 487c535
Showing 1 changed file with 30 additions and 25 deletions.
55 changes: 30 additions & 25 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,32 @@ module.exports = {
uvExceptionWithHostPort,
};

function determineSpecificType(value) {
let type = '';

if (value == null) {
type += value;
} else if (typeof value === 'function' && value.name) {
type = `function ${value.name}`;
} else if (typeof value === 'object') {
if (value.constructor?.name) {
type = `an instance of ${value.constructor.name}`;
} else {
const inspected = lazyInternalUtilInspect()
.inspect(value, { depth: -1 });
type += inspected;
}
} else {
let inspected = lazyInternalUtilInspect()
.inspect(value, { colors: false });
if (inspected.length > 25)
inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`;
type = `type ${typeof value} (${inspected})`;
}

return type;
}

// To declare an error message, use the E(sym, val, def) function above. The sym
// must be an upper case string. The val can be either a function or a string.
// The def must be an error class.
Expand Down Expand Up @@ -1237,25 +1263,8 @@ E('ERR_INVALID_ARG_TYPE',
}
}

if (actual == null) {
msg += `. Received ${actual}`;
} else if (typeof actual === 'function' && actual.name) {
msg += `. Received function ${actual.name}`;
} else if (typeof actual === 'object') {
if (actual.constructor?.name) {
msg += `. Received an instance of ${actual.constructor.name}`;
} else {
const inspected = lazyInternalUtilInspect()
.inspect(actual, { depth: -1 });
msg += `. Received ${inspected}`;
}
} else {
let inspected = lazyInternalUtilInspect()
.inspect(actual, { colors: false });
if (inspected.length > 25)
inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`;
msg += `. Received type ${typeof actual} (${inspected})`;
}
msg += `. Received ${determineSpecificType(actual)}`;

return msg;
}, TypeError);
E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
Expand Down Expand Up @@ -1335,12 +1344,8 @@ E('ERR_INVALID_RETURN_PROPERTY_VALUE', (input, name, prop, value) => {
` "${name}" function but got ${type}.`;
}, TypeError);
E('ERR_INVALID_RETURN_VALUE', (input, name, value) => {
let type;
if (value?.constructor?.name) {
type = `instance of ${value.constructor.name}`;
} else {
type = `type ${typeof value}`;
}
const type = determineSpecificType(value);

return `Expected ${input} to be returned from the "${name}"` +
` function but got ${type}.`;
}, TypeError, RangeError);
Expand Down

0 comments on commit 487c535

Please sign in to comment.