diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index e7b0063318c8c8..017c7c664e4080 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1955,7 +1955,7 @@ function formatError(err, constructor, tag, ctx, keys) { } name ??= 'Error'; - if ('cause' in err && + if (ObjectPrototypeHasOwnProperty(err, 'cause') && (keys.length === 0 || !ArrayPrototypeIncludes(keys, 'cause'))) { ArrayPrototypePush(keys, 'cause'); } @@ -1963,7 +1963,7 @@ function formatError(err, constructor, tag, ctx, keys) { // Print errors aggregated into AggregateError try { const errors = err.errors; - if (ArrayIsArray(errors) && + if (ArrayIsArray(errors) && ObjectPrototypeHasOwnProperty(err, 'errors') && (keys.length === 0 || !ArrayPrototypeIncludes(keys, 'errors'))) { ArrayPrototypePush(keys, 'errors'); } diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index d64c676d6403f9..e60320d0591233 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -688,6 +688,53 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); ); } +{ + // No own errors or cause property. + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + + const e1 = new Error('e1'); + const e2 = new TypeError('e2'); + const e3 = false; + + const errors = [e1, e2, e3]; + const aggregateError = new AggregateError(errors, 'Foobar'); + + assert.deepStrictEqual(aggregateError.errors, errors); + assert.strictEqual( + util.inspect(aggregateError), + '[AggregateError: Foobar] {\n [errors]: [ [Error: e1], [TypeError: e2], false ]\n}' + ); + + + const custom = new Error('No own errors property'); + Object.setPrototypeOf(custom, aggregateError); + + assert.strictEqual( + util.inspect(custom), + '[AggregateError: No own errors property]' + ); + + const cause = [new Error('cause')]; + const causeError = new TypeError('Foobar', { cause: [new Error('cause')] }); + + assert.strictEqual( + util.inspect(causeError), + '[TypeError: Foobar] { [cause]: [ [Error: cause] ] }' + ); + + const custom2 = new Error('No own cause property'); + Object.setPrototypeOf(custom2, causeError); + + assert.deepStrictEqual(custom2.cause, cause); + assert.strictEqual( + util.inspect(custom2), + '[TypeError: No own cause property]' + ); + + Error.stackTraceLimit = stackTraceLimit; +} + { const tmp = Error.stackTraceLimit; // Force stackTraceLimit = 0 for this test, but make it non-enumerable