From cbb362736bcec97aa3294d983bcab87ff661a465 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 31 Mar 2023 18:27:52 +0200 Subject: [PATCH] util: fix inspecting error with a throwing getter for `cause` PR-URL: https://github.com/nodejs/node/pull/47163 Reviewed-By: Moshe Atlow Reviewed-By: Yagiz Nizipli Reviewed-By: Luigi Pinca Reviewed-By: Chengzhong Wu --- lib/internal/util/inspect.js | 11 +++++++++-- test/message/util-inspect-error-cause.js | 6 ++++++ test/message/util-inspect-error-cause.out | 10 ++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index e6db302e9be719..57ffa96c97da40 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1243,9 +1243,16 @@ function getStackString(error) { function getStackFrames(ctx, err, stack) { const frames = StringPrototypeSplit(stack, '\n'); + let cause; + try { + ({ cause } = err); + } catch { + // If 'cause' is a getter that throws, ignore it. + } + // Remove stack frames identical to frames in cause. - if (err.cause && isError(err.cause)) { - const causeStack = getStackString(err.cause); + if (cause != null && isError(cause)) { + const causeStack = getStackString(cause); const causeStackStart = StringPrototypeIndexOf(causeStack, '\n at'); if (causeStackStart !== -1) { const causeFrames = StringPrototypeSplit(StringPrototypeSlice(causeStack, causeStackStart + 1), '\n'); diff --git a/test/message/util-inspect-error-cause.js b/test/message/util-inspect-error-cause.js index d34a908d374975..ed9d8230fe0c40 100644 --- a/test/message/util-inspect-error-cause.js +++ b/test/message/util-inspect-error-cause.js @@ -46,3 +46,9 @@ process.nextTick(() => { console.log(inspect(cause3)); console.log(inspect(error2)); }); + +{ + const error = new Error('cause that throws'); + Reflect.defineProperty(error, 'cause', { get() { throw new Error(); } }); + console.log(inspect(error)); +} diff --git a/test/message/util-inspect-error-cause.out b/test/message/util-inspect-error-cause.out index c7a04f4a09309c..73f0a673d76e1f 100644 --- a/test/message/util-inspect-error-cause.out +++ b/test/message/util-inspect-error-cause.out @@ -33,6 +33,16 @@ Error: undefined cause at * { [cause]: undefined } +Error: cause that throws + at * + at * + at * + at * + at * + at * + at * { + [cause]: [Getter] +} RangeError: New Stack Frames at * *[90m at *[39m {