diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index c611eb97fc0755..705a193c5b0eb0 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1359,6 +1359,14 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { return ctx.stylize(base, 'date'); } } else if (isError(value)) { + if (recurseTimes > ctx.depth && ctx.depth !== null) { + let name = 'Error'; + let msg = ''; + try { if (typeof value.name === 'string') name = value.name; } catch { /* getter throws */ } + try { if (typeof value.message === 'string') msg = value.message; } catch { /* getter throws */ } + return ctx.stylize( + msg !== '' ? `[${name}: ${msg}]` : `[${name}]`, 'special'); + } base = formatError(value, constructor, tag, ctx, keys); if (keys.length === 0 && protoProps === undefined) return base; diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index e60320d0591233..88f3580a91dff5 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -4033,3 +4033,27 @@ ${error.stack.split('\n').slice(1).join('\n')}`, assert.match(inspect(DOMException.prototype), /^\[object DOMException\] \{/); delete Error[Symbol.hasInstance]; } + +// Test that errors respect the depth option, same as other objects. +{ + // At depth: -1, errors should be abbreviated like [Object] for plain objects. + assert.strictEqual(inspect(new Error('msg'), { depth: -1 }), '[Error: msg]'); + assert.strictEqual(inspect(new TypeError('bad'), { depth: -1 }), '[TypeError: bad]'); + assert.strictEqual(inspect(new RangeError('oob'), { depth: -1 }), '[RangeError: oob]'); + + // No message → just [ErrorName] + assert.strictEqual(inspect(new Error(), { depth: -1 }), '[Error]'); + + // Custom name property + const customErr = new Error('test'); + customErr.name = 'MyError'; + assert.strictEqual(inspect(customErr, { depth: -1 }), '[MyError: test]'); + + // Errors nested inside an object at depth: 0 should be abbreviated, + // just as nested plain objects are shown as [Object]. + const wrapper = { err: new TypeError('oops'), obj: { a: 1 } }; + const result = inspect(wrapper, { depth: 0 }); + assert.match(result, /\[TypeError: oops\]/); + assert.match(result, /\[Object\]/); + assert(!result.includes(' at '), 'stack trace should not appear at depth 0'); +}