diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 659fd7b671e742..563ab00262a356 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1282,7 +1282,7 @@ function formatError(err, constructor, tag, ctx, keys) { removeDuplicateErrorKeys(ctx, keys, err, stack); - if (err.cause !== undefined && + if ('cause' in err && (keys.length === 0 || !keys.includes('cause'))) { keys.push('cause'); } diff --git a/test/message/util-inspect-error-cause.js b/test/message/util-inspect-error-cause.js index 4f22a34056cf4d..64ce5ee61913bb 100644 --- a/test/message/util-inspect-error-cause.js +++ b/test/message/util-inspect-error-cause.js @@ -22,6 +22,9 @@ const cause5 = new Error('Object cause', { ' at Module._compile (node:internal/modules/cjs/loader:827:30)' } }); +const cause6 = new Error('undefined cause', { + cause: undefined +}); console.log(cause4); console.log(cause5); diff --git a/test/message/util-inspect-error-cause.out b/test/message/util-inspect-error-cause.out index a34ca5b46c8d47..456ed97850b1b9 100644 --- a/test/message/util-inspect-error-cause.out +++ b/test/message/util-inspect-error-cause.out @@ -23,6 +23,17 @@ Error: Object cause ' at Module._compile (node:internal/modules/cjs/loader:827:30)' } } +Error: undefined cause + at * + at * + at * + at * + at * + at * + at * { + [cause]: undefined + } +} RangeError: New Stack Frames at * *[90m at *[39m { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 07461224847d47..47562b1fd2e870 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -665,9 +665,12 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); delete falsyCause1.stack; const falsyCause2 = new Error(undefined, { cause: null }); falsyCause2.stack = ''; + const undefinedCause = new Error('', { cause: undefined }); + undefinedCause.stack = ''; assert.strictEqual(util.inspect(falsyCause1), '[Error] { [cause]: false }'); assert.strictEqual(util.inspect(falsyCause2), '[Error] { [cause]: null }'); + assert.strictEqual(util.inspect(undefinedCause), '[Error] { [cause]: undefined }'); } {