Skip to content

Commit 2e0f93d

Browse files
committed
util: respect depth option for Error objects in inspect
Signed-off-by: Daijiro Wachi <daijiro.wachi@gmail.com>
1 parent 19c46ab commit 2e0f93d

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

lib/internal/util/inspect.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1359,6 +1359,14 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
13591359
return ctx.stylize(base, 'date');
13601360
}
13611361
} else if (isError(value)) {
1362+
if (recurseTimes > ctx.depth && ctx.depth !== null) {
1363+
let name = 'Error';
1364+
let msg = '';
1365+
try { if (typeof value.name === 'string') name = value.name; } catch { /* getter throws */ }
1366+
try { if (typeof value.message === 'string') msg = value.message; } catch { /* getter throws */ }
1367+
return ctx.stylize(
1368+
msg !== '' ? `[${name}: ${msg}]` : `[${name}]`, 'special');
1369+
}
13621370
base = formatError(value, constructor, tag, ctx, keys);
13631371
if (keys.length === 0 && protoProps === undefined)
13641372
return base;

test/parallel/test-util-inspect.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4033,3 +4033,27 @@ ${error.stack.split('\n').slice(1).join('\n')}`,
40334033
assert.match(inspect(DOMException.prototype), /^\[object DOMException\] \{/);
40344034
delete Error[Symbol.hasInstance];
40354035
}
4036+
4037+
// Test that errors respect the depth option, same as other objects.
4038+
{
4039+
// At depth: -1, errors should be abbreviated like [Object] for plain objects.
4040+
assert.strictEqual(inspect(new Error('msg'), { depth: -1 }), '[Error: msg]');
4041+
assert.strictEqual(inspect(new TypeError('bad'), { depth: -1 }), '[TypeError: bad]');
4042+
assert.strictEqual(inspect(new RangeError('oob'), { depth: -1 }), '[RangeError: oob]');
4043+
4044+
// No message → just [ErrorName]
4045+
assert.strictEqual(inspect(new Error(), { depth: -1 }), '[Error]');
4046+
4047+
// Custom name property
4048+
const customErr = new Error('test');
4049+
customErr.name = 'MyError';
4050+
assert.strictEqual(inspect(customErr, { depth: -1 }), '[MyError: test]');
4051+
4052+
// Errors nested inside an object at depth: 0 should be abbreviated,
4053+
// just as nested plain objects are shown as [Object].
4054+
const wrapper = { err: new TypeError('oops'), obj: { a: 1 } };
4055+
const result = inspect(wrapper, { depth: 0 });
4056+
assert.match(result, /\[TypeError: oops\]/);
4057+
assert.match(result, /\[Object\]/);
4058+
assert(!result.includes(' at '), 'stack trace should not appear at depth 0');
4059+
}

0 commit comments

Comments
 (0)