util: inspect: do not crash on an Error stack that contains a Symbol

See #56570

PR-URL: https://github.com/nodejs/node/pull/56573
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Jason Zhang <xzha4350@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
This commit is contained in:
Jordan Harband authored and Antoine du Hamel committed 2025-01-30 10:44:33 +01:00
1 parent 649cf0c0f6
commit a9d332a16f
2 files changed
+26 -8

No files matched your search

+10 -4
View File
@@ -1287,8 +1287,14 @@ function identicalSequenceRange(a, b) {
return { len: 0, offset: 0 };
}
function getStackString(error) {
return error.stack ? String(error.stack) : ErrorPrototypeToString(error);
function getStackString(ctx, error) {
if (error.stack) {
if (typeof error.stack === 'string') {
return error.stack;
}
return formatValue(ctx, error.stack);
}
return ErrorPrototypeToString(error);
}
function getStackFrames(ctx, err, stack) {
@@ -1303,7 +1309,7 @@ function getStackFrames(ctx, err, stack) {
// Remove stack frames identical to frames in cause.
if (cause != null && isError(cause)) {
const causeStack = getStackString(cause);
const causeStack = getStackString(ctx, cause);
const causeStackStart = StringPrototypeIndexOf(causeStack, '\n at');
if (causeStackStart !== -1) {
const causeFrames = StringPrototypeSplit(StringPrototypeSlice(causeStack, causeStackStart + 1), '\n');
@@ -1426,7 +1432,7 @@ function safeGetCWD() {
function formatError(err, constructor, tag, ctx, keys) {
const name = err.name != null ? err.name : 'Error';
let stack = getStackString(err);
let stack = getStackString(ctx, err);
removeDuplicateErrorKeys(ctx, keys, err, stack);
+16 -4
View File
@@ -777,16 +777,18 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
[undefined, 'RangeError: foo', '[RangeError: foo]'],
[false, 'false [RangeError]: foo', '[RangeError: foo]'],
['', 'foo', '[RangeError: foo]'],
[[1, 2, 3], '1,2,3 [RangeError]: foo', '[1,2,3]'],
[[1, 2, 3], '1,2,3 [RangeError]: foo', '[[\n 1,\n 2,\n 3\n]]'],
].forEach(([value, outputStart, stack]) => {
let err = new RangeError('foo');
err.name = value;
const result = util.inspect(err);
assert(
util.inspect(err).startsWith(outputStart),
result.startsWith(outputStart),
util.format(
'The name set to %o did not result in the expected output "%s"',
'The name set to %o did not result in the expected output "%s", got "%s"',
value,
outputStart
outputStart,
result.split('\n')[0]
)
);
@@ -3416,3 +3418,13 @@ assert.strictEqual(
${error.stack.split('\n').slice(1).join('\n')}`,
);
}
{
const error = new Error();
error.stack = [Symbol('foo')];
assert.strictEqual(
inspect(error),
'[[\n Symbol(foo)\n]]'
);
}