diff --git a/cli/js/console.ts b/cli/js/console.ts index 9f0ce4bd6e52f7c2070da978b8d3518adef2ef7f..e6b54d8c124692738be4d6c9d6c77445630b6868 100644 --- a/cli/js/console.ts +++ b/cli/js/console.ts @@ -327,8 +327,11 @@ function createObjectString( ...args: [ConsoleContext, number, number] ): string { if (customInspect in value && typeof value[customInspect] === "function") { - return String(value[customInspect]!()); - } else if (value instanceof Error) { + try { + return String(value[customInspect]!()); + } catch {} + } + if (value instanceof Error) { return String(value.stack); } else if (Array.isArray(value)) { return createArrayString(value, ...args); diff --git a/cli/js/console_test.ts b/cli/js/console_test.ts index 903e65a82e95a5f7abe9404dfc8926e82bbdaafc..50fe1d66a0de5295f934b5dd23feef9fe862d0d9 100644 --- a/cli/js/console_test.ts +++ b/cli/js/console_test.ts @@ -190,6 +190,27 @@ test(function consoleTestWithCustomInspector(): void { assertEquals(stringify(new A()), "b"); }); +test(function consoleTestWithCustomInspectorError(): void { + class A { + [customInspect](): string { + throw new Error("BOOM"); + return "b"; + } + } + + assertEquals(stringify(new A()), "A {}"); + + class B { + constructor(public field: { a: string }) {} + [customInspect](): string { + return this.field.a; + } + } + + assertEquals(stringify(new B({ a: "a" })), "a"); + assertEquals(stringify(B.prototype), "{}"); +}); + test(function consoleTestWithIntegerFormatSpecifier(): void { assertEquals(stringify("%i"), "%i"); assertEquals(stringify("%i", 42.0), "42");