Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
25 changes: 22 additions & 3 deletions src/jsc/bindings/ErrorCode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,32 @@
return ErrorInstance::createStructure(vm, globalObject, prototype);
}

static Structure* createErrorStructure(JSC::VM& vm, JSGlobalObject* globalObject, ErrorCode code)
{
const auto& data = errors[static_cast<size_t>(code)];
auto* prototype = createErrorPrototype(vm, globalObject, data.type, data.name, data.code);

// Node's ERR_* errors are plain Error/TypeError/RangeError instances carrying a `code`, so those
// prototypes keep inheriting `constructor` from the base error. AbortError is a real
// `class AbortError extends Error` in Node, and util.inspect() / determineSpecificType() print
// the name of `err.constructor`, so its shared prototype gets the shape that class would have.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (code == ErrorCode::ABORT_ERR) {
auto* constructor = JSC::JSFunction::create(vm, globalObject, 0, "AbortError"_s, jsFunctionMakeAbortError, JSC::ImplementationVisibility::Public, JSC::NoIntrinsic, jsFunctionMakeAbortError);
constructor->setPrototypeDirect(vm, globalObject->errorConstructor());
constructor->putDirect(vm, vm.propertyNames->prototype, prototype, JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly);
prototype->putDirect(vm, vm.propertyNames->constructor, constructor, JSC::PropertyAttribute::DontEnum | 0);
}

return ErrorInstance::createStructure(vm, globalObject, prototype);
}

JSObject* ErrorCodeCache::createError(VM& vm, Zig::GlobalObject* globalObject, ErrorCode code, JSValue message, JSValue options)
{
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
auto* cache = errorCache(globalObject);
const auto& data = errors[static_cast<size_t>(code)];
if (!cache->internalField(static_cast<unsigned>(code))) {
auto* structure = createErrorStructure(vm, globalObject, data.type, data.name, data.code);
auto* structure = createErrorStructure(vm, globalObject, code);
cache->internalField(static_cast<unsigned>(code)).set(vm, cache, structure);
}

Expand Down Expand Up @@ -248,7 +267,7 @@
if (auto* zigGlobalObject = dynamicDowncast<Zig::GlobalObject>(globalObject))
return createError(vm, zigGlobalObject, code, message, jsUndefined());

auto* structure = createErrorStructure(vm, globalObject, errors[static_cast<size_t>(code)].type, errors[static_cast<size_t>(code)].name, errors[static_cast<size_t>(code)].code);
auto* structure = createErrorStructure(vm, globalObject, code);
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
String messageString = message.isUndefined() ? String() : message.toWTFString(globalObject);
if (scope.exception() && !vm.hasPendingTerminationException())
Expand Down Expand Up @@ -1756,7 +1775,7 @@
return JSC::JSValue::encode(error);
}

JSC_DEFINE_HOST_FUNCTION(jsFunctionMakeAbortError, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
JSC_DEFINE_HOST_FUNCTION(Bun::jsFunctionMakeAbortError, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))

Check warning on line 1778 in src/jsc/bindings/ErrorCode.cpp

View check run for this annotation

Claude / Claude Code Review

AbortError constructor accepts primitive number/boolean options without throwing

The `options` validation in `jsFunctionMakeAbortError` only rejects non-object *cells* — numbers and booleans are immediate JSValues (not cells), so `options.isCell()` is false and `new err.constructor('m', 42)` / `new err.constructor('m', true)` silently succeed, whereas Node throws `ERR_INVALID_ARG_TYPE`. This is pre-existing code, but this PR newly exposes it as the user-reachable `err.constructor` and claims Node parity for this check; changing the guard to `!options.isUndefinedOrNull() && !
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
{
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
auto& vm = JSC::getVM(globalObject);
Expand Down
2 changes: 2 additions & 0 deletions src/jsc/bindings/ErrorCode.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ JSObject* createInvalidThisError(JSGlobalObject* globalObject, JSValue thisValue
JSObject* createInvalidThisError(JSGlobalObject* globalObject, const String& message);

JSC_DECLARE_HOST_FUNCTION(jsFunctionMakeErrorWithCode);
// `$makeAbortError` for the JS builtins, and the `constructor` of every ABORT_ERR error.
JSC_DECLARE_HOST_FUNCTION(jsFunctionMakeAbortError);

// Appends Node's `determineSpecificType()` rendering of a value ("type number (5)",
// "an instance of Foo", ...) — the "Received ..." part of ERR_INVALID_ARG_TYPE messages.
Expand Down
2 changes: 0 additions & 2 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,6 @@ BUN_DECLARE_HOST_FUNCTION(BUN__HTTP2__getUnpackedSettings);
BUN_DECLARE_HOST_FUNCTION(BUN__HTTP2_getPackedSettings);
BUN_DECLARE_HOST_FUNCTION(BUN__HTTP2_assertSettings);

JSC_DECLARE_HOST_FUNCTION(jsFunctionMakeAbortError);

using JSGlobalObject = JSC::JSGlobalObject;
using Exception = JSC::Exception;
using JSValue = JSC::JSValue;
Expand Down
143 changes: 143 additions & 0 deletions test/js/node/errors/abort-error-constructor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { describe, expect, test } from "bun:test";
import { EventEmitter, once } from "node:events";
import { readFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
import { inspect } from "node:util";

// Node's AbortError is `class AbortError extends Error` (lib/internal/errors.js), so
// `err.constructor` is a function named AbortError. Bun builds these errors natively
// (ErrorCode.cpp) from two entry points, `$makeAbortError` in the JS builtins and
// `Bun__wrapAbortError` for Rust callers; both must produce the same class shape.
// Except for the bun:test formatting case, every assertion here also holds on Node v26.

async function rejection(promise: Promise<unknown>): Promise<any> {
try {
await promise;
} catch (e) {
return e;
}
throw new Error("expected the operation to reject");
}

function thrown(fn: () => unknown): any {
try {
fn();
} catch (e) {
return e;
}
throw new Error("expected the operation to throw");
}

async function abortErrors() {
const signal = AbortSignal.abort();
return {
// $makeAbortError (JS builtins)
"timers/promises": await rejection(sleep(1, undefined, { signal })),
"events.once": await rejection(once(new EventEmitter(), "never", { signal })),
// Bun__wrapAbortError (Rust callers)
"fs.promises.readFile": await rejection(readFile(import.meta.path, { signal })),
"Bun.spawn": thrown(() => Bun.spawn({ cmd: ["this-command-is-never-spawned"], signal })),
};
}

describe("node-style AbortError", () => {
test("util.inspect prints it under its own class name", async () => {
const errors = await abortErrors();
const firstLines = Object.fromEntries(
Object.entries(errors).map(([producer, err]) => [producer, inspect(err).split("\n")[0]]),
);
expect(firstLines).toEqual({
"timers/promises": "AbortError: The operation was aborted",
"events.once": "AbortError: The operation was aborted",
"fs.promises.readFile": "AbortError: The operation was aborted",
"Bun.spawn": "AbortError: The operation was aborted",
});
});

test("every producer shares one AbortError class", async () => {
const errors = await abortErrors();
const AbortError = errors["timers/promises"].constructor;
const prototype = Object.getPrototypeOf(errors["timers/promises"]);

for (const err of Object.values(errors)) {
expect(err.constructor).toBe(AbortError);
expect(err).toBeInstanceOf(AbortError);
expect(Object.getPrototypeOf(err)).toBe(prototype);
}

expect(AbortError).not.toBe(Error);
expect({ name: AbortError.name, length: AbortError.length }).toEqual({ name: "AbortError", length: 0 });
expect(AbortError.prototype).toBe(prototype);
expect(Object.getPrototypeOf(AbortError)).toBe(Error);
expect(Object.getPrototypeOf(prototype)).toBe(Error.prototype);

// Same attributes `class AbortError extends Error {}` would produce.
const { value: constructorValue, ...constructorAttributes } = Object.getOwnPropertyDescriptor(
prototype,
"constructor",
)!;
expect(constructorValue).toBe(AbortError);
expect(constructorAttributes).toEqual({ writable: true, enumerable: false, configurable: true });
const { value: prototypeValue, ...prototypeAttributes } = Object.getOwnPropertyDescriptor(AbortError, "prototype")!;
expect(prototypeValue).toBe(prototype);
expect(prototypeAttributes).toEqual({ writable: false, enumerable: false, configurable: false });
});

test("err.constructor constructs AbortErrors", async () => {
const { "timers/promises": err } = await abortErrors();
const AbortError = err.constructor;
const cause = new Error("why");

const custom = new AbortError("custom message", { cause });
expect(custom).toBeInstanceOf(AbortError);
expect({ name: custom.name, code: custom.code, message: custom.message, cause: custom.cause }).toEqual({
name: "AbortError",
code: "ABORT_ERR",
message: "custom message",
cause,
});
expect(inspect(custom).split("\n")[0]).toBe("AbortError: custom message");

const defaults = new AbortError();
expect(defaults).toBeInstanceOf(AbortError);
expect({ name: defaults.name, code: defaults.code, message: defaults.message, cause: defaults.cause }).toEqual({
name: "AbortError",
code: "ABORT_ERR",
message: "The operation was aborted",
cause: undefined,
});

const invalid = thrown(() => new AbortError("message", "not an object"));
expect({ name: invalid.name, code: invalid.code, message: invalid.message }).toEqual({
name: "TypeError",
code: "ERR_INVALID_ARG_TYPE",
message: `The "options" argument must be of type object. Received type string ('not an object')`,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

test("ERR_INVALID_ARG_TYPE describes it as an instance of AbortError", async () => {
const { "fs.promises.readFile": err } = await abortErrors();
const invalid = thrown(() => Buffer.from(err));
expect({ code: invalid.code, message: invalid.message }).toEqual({
code: "ERR_INVALID_ARG_TYPE",
message:
"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of AbortError",
});
});

test("bun:test formats it under its class name, like jest does for node's AbortError", async () => {
const { "events.once": err } = await abortErrors();
expect(err).toMatchInlineSnapshot(`[AbortError: The operation was aborted]`);
});

test("ERR_* errors still report the base constructor, like node", () => {
// Node keeps `constructor` pointing at the base class for its ERR_* codes; only
// AbortError is a class of its own.
const err = thrown(() => Buffer.from(1 as any));
expect({ code: err.code, constructor: err.constructor, name: err.name }).toEqual({
code: "ERR_INVALID_ARG_TYPE",
constructor: TypeError,
name: "TypeError",
});
});
});
Loading