diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 7570315abe54d6..24b96cd0039796 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -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. @@ -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') => { @@ -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);