Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Loading