Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/jsc/Exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ unsafe extern "C" {
global: &JSGlobalObject,
stack: &mut ZigStackTrace,
);
safe fn JSC__Exception__asJSValue(this: &Exception) -> JSValue;
}

impl Exception {
pub(crate) fn get_stack_trace(&self, global: &JSGlobalObject, stack: &mut ZigStackTrace) {
JSC__Exception__getStackTrace(self, global, stack);
}

pub fn value(&self) -> JSValue {
JSC__Exception__asJSValue(self)
/// The `JSC::Exception` cell itself; `JSValue::to_error` unwraps it to the thrown value.
pub fn to_js(&self) -> JSValue {
JSValue::from_cell(self)
}
}
10 changes: 8 additions & 2 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4813,8 +4813,14 @@ impl VirtualMachine {
) {
let mut formatter = crate::console_object::Formatter::new(self.global());
let colors = bun_core::Output::enable_ansi_colors_stderr();
let exception_cell = exception.to_js();
// An Error carries its own stack, properties and cause; anything else only has the cell's throw site.
let value = match exception_cell.to_error() {
Some(error) if error.is_error() => error,
_ => exception_cell,
Comment thread
robobun marked this conversation as resolved.
Resolved
};
Comment thread
robobun marked this conversation as resolved.
Resolved
self.print_errorlike_object(
exception.value(),
value,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Some(exception),
exception_list,
&mut formatter,
Expand Down Expand Up @@ -5373,7 +5379,7 @@ impl VirtualMachine {
exception: &Exception,
) -> JSValue {
let jsc_vm = global_object.bun_vm().as_mut();
let _ = jsc_vm.uncaught_exception(global_object, exception.value(), false);
let _ = jsc_vm.uncaught_exception(global_object, exception.to_js(), false);
JSValue::UNDEFINED
}

Expand Down
5 changes: 0 additions & 5 deletions src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4875,11 +4875,6 @@ bool JSC__JSValue__stringIncludes(JSC::EncodedJSValue value, JSC::JSGlobalObject
return stringToSearchIn.find(searchString, 0) != WTF::notFound;
}

extern "C" JSC::EncodedJSValue JSC__Exception__asJSValue(JSC::Exception* exception)
{
return JSC::JSValue::encode(exception);
}

void JSC__VM__releaseWeakRefs(JSC::VM* arg0)
{
arg0->finalizeSynchronousJSExecution();
Expand Down
2 changes: 1 addition & 1 deletion test/js/bun/test/dots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ test("dots 2", async () => {
6 | setTimeout(() => {
7 | resolve();
8 | throw new Error("unhandled error");
^
^
error: unhandled error
at <anonymous> (file:NN:NN)
(fail) failure
Expand Down
2 changes: 1 addition & 1 deletion test/js/bun/test/only-failures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ test.concurrent("only-failures flag should show only failures", async () => {
24 |
25 | test("another failing test", () => {
26 | throw new Error("This test fails");
^
^
error: This test fails
at <anonymous> (file:NN:NN)
(fail) another failing test
Expand Down
256 changes: 254 additions & 2 deletions test/js/bun/test/stack.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { $ } from "bun";
import { expect, test } from "bun:test";
import { bunEnv, bunExe, bunRun, normalizeBunSnapshot } from "harness";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, bunRun, normalizeBunSnapshot, tempDir } from "harness";
import { join } from "node:path";

test("name property is used for function calls in Error.stack", () => {
Expand Down Expand Up @@ -175,3 +175,255 @@ test("Async functions frame should be included in stack trace", async () => {
at async <anonymous> (file:NN:NN)"
`);
});

describe("uncaught error printer", () => {
// A callback invoked from native code (timers, the microtask queue, process
// lifecycle events) hands an error that escapes it to the printer wrapped in
// a JSC::Exception. The printer must still print the Error itself: the stack
// captured where it was constructed, its own properties and its cause, so
// the output is the same as when the same error escapes synchronously.
const exceptionEntryPoints = ["setTimeout", "setImmediate", "queueMicrotask", "beforeExit", "exit"];
// nextTick callbacks run from JS, which reports the bare thrown value.
const entryPoints = [...exceptionEntryPoints, "nextTick"];

const fixture = `const [, , entryPoint, kind] = process.argv;
function make(message, options) {
const err = new Error(message, options);
err.code = "E_FIXTURE";
return err;
}
function thrower() {
const err =
kind === "aggregate"
? new AggregateError([make("first"), make("second")], "two errors")
: make("printed from the error itself", kind === "error" ? { cause: make("the cause") } : undefined);
if (kind === "materialized") console.log(err.stack);
throw err;
}
function throwString() {
throw "not an error instance";
}
const callback = kind === "string" ? throwString : thrower;
switch (entryPoint) {
case "sync": callback(); break;
case "nextTick": process.nextTick(callback); break;
case "setTimeout": setTimeout(callback, 1); break;
case "setImmediate": setImmediate(callback); break;
case "queueMicrotask": queueMicrotask(callback); break;
case "beforeExit": process.on("beforeExit", callback); break;
case "exit": process.on("exit", callback); break;
case "rethrow": process.on("uncaughtException", err => { throw err; }); callback(); break;
}
`;

// Debug builds show builtin frames unless told otherwise.
const env = { BUN_JSC_showPrivateScriptsInStackTraces: "0" };

async function run(dir: string, entryPoint: string, kind: string) {
const { stdout, stderr, exitCode } = await bunRun([join(dir, "fixture.js"), entryPoint, kind], env);
const normalize = (text: string) => text.replaceAll(dir, "<dir>").replaceAll("\\", "/");
return { stdout: normalize(stdout), stderr: normalize(stderr), exitCode };
}

// Keeps exactly the part of the output that is derived from the thrown
// error. The entry points legitimately differ in the frames below `thrower`
// (the synchronous variant has a top-level frame, the others were called
// from native code), and the trailer names the build.
function errorOwnedOutput({ stderr, exitCode }: { stderr: string; exitCode: number }) {
const output = stderr
.split("\n")
.filter(line => !/^\s+at (?!make |thrower )/.test(line) && !line.startsWith("Bun v"))
.join("\n")
.trim();
return { exitCode, output };
}

// Columns inside the transpiled module are not the subject here; the lines
// (which source line the caret and the frames point at) are.
const withoutColumns = (output: string) =>
output.replace(/:(\d+):\d+(\)?)$/gm, ":$1:<col>$2").replace(/^ +\^$/gm, "^");

const frameLines = (text: string) =>
text
.split("\n")
.filter(line => /^\s+at /.test(line))
.map(line => line.trim());

async function compareWithSynchronousThrow(kind: string) {
using dir = tempDir("uncaught-print", { "fixture.js": fixture });
const [sync, ...results] = await Promise.all(
["sync", ...entryPoints].map(entryPoint => run(String(dir), entryPoint, kind)),
);
const expected = errorOwnedOutput(sync);
expect(Object.fromEntries(entryPoints.map((entryPoint, i) => [entryPoint, errorOwnedOutput(results[i])]))).toEqual(
Object.fromEntries(entryPoints.map(entryPoint => [entryPoint, expected])),
);
return { ...expected, results };
}

test.concurrent("an Error escaping a native entry point prints like a synchronous throw", async () => {
const { exitCode, output } = await compareWithSynchronousThrow("error");
expect(withoutColumns(output)).toMatchInlineSnapshot(`
"1 | const [, , entryPoint, kind] = process.argv;
2 | function make(message, options) {
3 | const err = new Error(message, options);
^
error: printed from the error itself
code: "E_FIXTURE"

at make (<dir>/fixture.js:3:<col>)
at thrower (<dir>/fixture.js:11:<col>)

1 | const [, , entryPoint, kind] = process.argv;
2 | function make(message, options) {
3 | const err = new Error(message, options);
^
error: the cause
code: "E_FIXTURE"

at make (<dir>/fixture.js:3:<col>)
at thrower (<dir>/fixture.js:11:<col>)"
`);
expect(exitCode).toBe(1);
});

test.concurrent(
"an AggregateError escaping a native entry point prints each of its errors like a synchronous throw",
async () => {
const { exitCode, output } = await compareWithSynchronousThrow("aggregate");
expect(output).toContain("error: first\n");
expect(output).toContain("error: second\n");
expect(exitCode).toBe(1);
},
);

test.concurrent(
"an Error whose .stack was already read is printed where error.stack says it was created",
async () => {
const { exitCode, results } = await compareWithSynchronousThrow("materialized");
for (const { stdout, stderr } of results) {
const [stackTop] = frameLines(stdout);
expect(stackTop).toStartWith("at make (<dir>/fixture.js:3:");
expect(frameLines(stderr)[0]).toBe(stackTop);
}
expect(exitCode).toBe(1);
},
);

// The error an uncaughtException listener rethrows is reported the same way
// (exit code 7 is the listener having thrown). https://github.com/oven-sh/bun/issues/30504
test.concurrent("an Error rethrown by an uncaughtException listener prints like a synchronous throw", async () => {
using dir = tempDir("uncaught-print", { "fixture.js": fixture });
const [sync, rethrown] = await Promise.all([
run(String(dir), "sync", "error"),
run(String(dir), "rethrow", "error"),
]);
expect(errorOwnedOutput(rethrown)).toEqual({ ...errorOwnedOutput(sync), exitCode: 7 });
});

async function runBunTest(dir: string, file: string) {
await using proc = Bun.spawn({
cmd: [bunExe(), "test", file],
cwd: dir,
env: { ...bunEnv, ...env },
stdout: "ignore",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
return { stderr, exitCode };
}

// `bun test` reports what a test body throws through the same printer.
test.concurrent("bun test prints an error thrown by a test from the error itself", async () => {
using dir = tempDir("uncaught-print", {
"throws.test.js": `import { test } from "bun:test";
function makeAndThrow() {
const err = new Error("outer", { cause: new Error("inner") });
err.code = "E_OUTER";
throw err;
}
test("throws", makeAndThrow);
`,
});
const { stderr, exitCode } = await runBunTest(String(dir), "throws.test.js");
expect(frameLines(stderr)).toEqual([
expect.stringMatching(/^at makeAndThrow \(.*throws\.test\.js:3:\d+\)$/),
expect.stringMatching(/^at makeAndThrow \(.*throws\.test\.js:3:\d+\)$/),
]);
expect(withoutColumns(normalizeBunSnapshot(stderr))).toMatchInlineSnapshot(`
"throws.test.js:
1 | import { test } from "bun:test";
2 | function makeAndThrow() {
3 | const err = new Error("outer", { cause: new Error("inner") });
^
error: outer
code: "E_OUTER"
at makeAndThrow (file:NN:NN)

1 | import { test } from "bun:test";
2 | function makeAndThrow() {
3 | const err = new Error("outer", { cause: new Error("inner") });
^
error: inner
at makeAndThrow (file:NN:NN)
(fail) throws

0 pass
1 fail
Ran 1 test across 1 file."
`);
expect(exitCode).toBe(1);
});

// Printing the error itself also means a stack rewritten with
// Error.captureStackTrace is honored. https://github.com/oven-sh/bun/issues/21211
test.concurrent("bun test honors Error.captureStackTrace on a thrown error", async () => {
using dir = tempDir("uncaught-print", {
"helper.ts": `export function fail(message: string) {
const error = new Error(message);
Error.captureStackTrace(error, fail);
throw error;
}
`,
"helper.test.ts": `import { test } from "bun:test";
import { fail } from "./helper";

test("something", () => {
fail("TEST FAILURE");
});
`,
});
const { stderr, exitCode } = await runBunTest(String(dir), "helper.test.ts");
expect(frameLines(stderr)).toEqual([expect.stringMatching(/^at <anonymous> \(.*helper\.test\.ts:5:\d+\)$/)]);
expect(withoutColumns(normalizeBunSnapshot(stderr))).toMatchInlineSnapshot(`
"helper.test.ts:
1 | import { test } from "bun:test";
2 | import { fail } from "./helper";
3 |
4 | test("something", () => {
5 | fail("TEST FAILURE");
^
error: TEST FAILURE
at <anonymous> (file:NN:NN)
(fail) something

0 pass
1 fail
Ran 1 test across 1 file."
`);
expect(exitCode).toBe(1);
});

test.concurrent(
"a thrown value that is not an Error is still printed with the frames of the throw site",
async () => {
using dir = tempDir("uncaught-print", { "fixture.js": fixture });
const results = await Promise.all(exceptionEntryPoints.map(entryPoint => run(String(dir), entryPoint, "string")));
for (const { stderr, exitCode } of results) {
expect(stderr).toContain("error: not an error instance\n");
expect(stderr).toMatch(/^\s+at throwString \(<dir>\/fixture\.js:16:\d+\)$/m);
expect(exitCode).toBe(1);
}
},
);
});
33 changes: 33 additions & 0 deletions test/js/node/process/process.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,39 @@ describe.concurrent(() => {
expect(await proc.stderr.text()).toContain("bar");
});

describe.each([
["rethrows", "throw err;"],
["reads err.stack and then rethrows", "void err.stack; throw err;"],
])("when the uncaughtException handler %s", (_, handlerBody) => {
it("prints the Error's own stack", async () => {
using dir = tempDir("rethrow-uncaught", {
"index.cjs": `
'use strict';
function rethrowHandler(err) {
${handlerBody}
}
process.on('uncaughtException', rethrowHandler);
function throwUncaughtError() {
throw new Error('Boom');
}
throwUncaughtError();
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), join(String(dir), "index.cjs")],
env: bunEnv,
stderr: "pipe",
stdout: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toBe("");
expect(stderr).toContain("Boom");
expect(stderr).toContain("at throwUncaughtError (");
expect(stderr).not.toContain("at rethrowHandler (");
expect(exitCode).toBe(7);
});
});

it("aborts when the uncaughtExceptionCaptureCallback throws", async () => {
const proc = Bun.spawn([bunExe(), join(import.meta.dir, "process-uncaughtExceptionCaptureCallbackAbort.js")], {
stderr: "pipe",
Expand Down
Loading
Loading