Skip to content
47 changes: 34 additions & 13 deletions src/js/node/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ function emitError(emitter, args) {
}
}

throwUnhandledError(args);
}

function throwUnhandledError(args): never {
let er: Error | undefined;
if (args.length > 0) er = args[0];

Expand Down Expand Up @@ -194,25 +198,33 @@ function applyHandlers(handlers, emitter, args) {
}
}

function addCatch(emitter, promise, type, args) {
promise.then(undefined, function (err) {
// The callback is called with nextTick to avoid a follow-up rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, emitter, err, type, args);
});
// Promises/A+: `then` is read once; a `then` getter that throws is an 'error'.
function addCatch(emitter, result, type, args) {
if (!emitter[kCapture]) return;
try {
const then = result.then;
if (typeof then === "function") {
then.$call(result, undefined, function (err) {
// The callback is called with nextTick to avoid a follow-up rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, emitter, err, type, args);
});
}
} catch (err) {
emitter.emit("error", err);
}
}

function emitUnhandledRejectionOrErr(emitter, err, type, args) {
if (typeof emitter[kRejection] === "function") {
emitter[kRejection](err, type, ...args);
} else {
// If the error handler throws, it is not catchable and it will end up in 'uncaughtException'.
// We restore the previous value of kCapture in case the uncaughtException is present
// and the exception is handled.
// Capture is off during the 'error' emit so a rejecting 'error' listener cannot loop.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
const prev = emitter[kCapture];
try {
emitter[kCapture] = false;
emitter.emit("error", err);
} finally {
emitter[kCapture] = true;
emitter[kCapture] = prev;
}
}
}
Expand Down Expand Up @@ -276,10 +288,14 @@ const emitWithoutRejectionCapture = function emit(type, ...args) {

const emitWithRejectionCapture = function emit(type, ...args) {
$debug(`${this.constructor?.name || "EventEmitter"}.emit`, type);
var { _events: events } = this;
if (type === "error") {
return emitError(this, args);
// As node: the monitor first, then 'error' listeners as ordinary (captured) listeners, or the throw.
if (events !== undefined && events[kErrorMonitor] !== undefined) {
emitWithRejectionCapture.$call(this, kErrorMonitor, ...args);
}
if (events === undefined || events.error === undefined) throwUnhandledError(args);
}
var { _events: events } = this;
if (events === undefined) return false;
var handler = events[type];
if (handler === undefined) return false;
Expand All @@ -303,7 +319,7 @@ const emitWithRejectionCapture = function emit(type, ...args) {
result = handler.$apply(this, args);
break;
}
if (result !== undefined && $isPromise(result)) {
if (result !== undefined && result !== null) {
addCatch(this, result, type, args);
}
return true;
Expand Down Expand Up @@ -331,7 +347,7 @@ const emitWithRejectionCapture = function emit(type, ...args) {
result = listener.$apply(this, args);
break;
}
if (result !== undefined && $isPromise(result)) {
if (result !== undefined && result !== null) {
addCatch(this, result, type, args);
}
}
Expand Down Expand Up @@ -995,6 +1011,11 @@ Object.defineProperties(EventEmitter, {
validateBoolean(value, "EventEmitter.captureRejections");

EventEmitterPrototype[kCapture] = value;
// An emitter whose constructor never ran has no own `emit`. A user's replacement stays.
const emit = EventEmitterPrototype.emit;
if (emit === emitWithoutRejectionCapture || emit === emitWithRejectionCapture) {
EventEmitterPrototype.emit = value ? emitWithRejectionCapture : emitWithoutRejectionCapture;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
},
enumerable: true,
},
Expand Down
24 changes: 22 additions & 2 deletions src/jsc/JSGlobalObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1120,8 +1120,27 @@ impl JSGlobalObject {

/// Runs the `unhandledRejection` machinery, which catches and reports its own exceptions; what
/// can come back is the VM's termination (taken at this boundary when at loop level).
#[inline]
pub fn handle_rejected_promises(&self) -> JsResult<()> {
crate::from_js_host_call_generic(self, || JSC__JSGlobalObject__handleRejectedPromises(self))
if !JSC__JSGlobalObject__hasRejectedPromises(self) {
return Ok(());
}
self.report_rejected_promises()
}

#[cold]
#[inline(never)]
fn report_rejected_promises(&self) -> JsResult<()> {
// As in Node, a batch's listeners all run before the ticks and microtasks they queued.
while crate::from_js_host_call_generic(self, || {
JSC__JSGlobalObject__handleRejectedPromises(self)
})? {
self.bun_vm()
.event_loop_mut()
.drain_microtasks()
.map_err(|stopped| stopped.throw(self))?;
}
Ok(())
}

// The `readableStreamTo*` consumers throw `ERR_INVALID_ARG_TYPE` when
Expand Down Expand Up @@ -1546,7 +1565,8 @@ unsafe extern "C" {
) -> JSValue;
safe fn JSC__JSGlobalObject__generateHeapSnapshot(this: &JSGlobalObject) -> JSValue;

safe fn JSC__JSGlobalObject__handleRejectedPromises(this: &JSGlobalObject);
safe fn JSC__JSGlobalObject__hasRejectedPromises(this: &JSGlobalObject) -> bool;
safe fn JSC__JSGlobalObject__handleRejectedPromises(this: &JSGlobalObject) -> bool;

safe fn ZigGlobalObject__readableStreamToArrayBuffer(
this: &JSGlobalObject,
Expand Down
44 changes: 17 additions & 27 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4331,42 +4331,40 @@ impl VirtualMachine {
) {
// Reported as it happens: it belongs to the context that is current.
let owner = Bun__ModuleGraph__rejecting(global_object);
self.unhandled_rejection_owned(global_object, reason, promise, owner);
if self.unhandled_rejection_owned(global_object, reason, promise, owner) {
let _ = self.event_loop_mut().drain_microtasks();
}
}

/// `owner`: the `Bun.ModuleGraph` in whose context the promise was rejected (its `onError`
/// takes it), or null. The tracker queue reports after the fact, so it decided when it happened.
#[must_use = "true: the caller owes a microtask checkpoint once its batch is reported"]
pub fn unhandled_rejection_owned(
&mut self,
global_object: &JSGlobalObject,
reason: JSValue,
promise: JSValue,
owner: JSValue,
) {
) -> bool {
use bun_options_types::schema::api::UnhandledRejections as Mode;

if self.is_shutting_down() || !self.script_allowed() || reason.is_termination_exception() {
bun_core::debug_warn!("unhandledRejection during shutdown.");
return;
return false;
}

if owner.is_cell()
&& Bun__ModuleGraph__handleUnhandledRejection(global_object, reason, owner)
{
let _ = self.event_loop_mut().drain_microtasks();
return;
return true;
}

if isBunTest.load(core::sync::atomic::Ordering::Relaxed) {
self.unhandled_error_counter += 1;
(self.on_unhandled_rejection)(self, global_object, reason);
return;
return false;
}

// Each arm drains microtasks on exit — hoisted into a closure.
let drain = |this: &mut Self| {
let _ = this.event_loop_mut().drain_microtasks();
};
// Wrapper over the `Bun__handleUnhandledRejection` FFI call (returns
// whether a JS handler claimed it). Captures `global_object` / `reason`
// / `promise` so the six branches below stay concise.
Expand All @@ -4386,32 +4384,26 @@ impl VirtualMachine {
match self.unhandled_rejections_mode() {
Mode::Bun => {
if handle_unhandled() {
return;
return true;
}
// continue to default handler
}
Mode::None => {
let _ = handle_unhandled();
drain(self);
return; // ignore the unhandled rejection
return true; // ignore the unhandled rejection
}
Mode::Warn => {
let _ = handle_unhandled();
emit_warning(self);
drain(self);
return;
return true;
}
Mode::WarnWithErrorCode => {
let handled = handle_unhandled();
if !handled {
emit_warning(self);
self.exit_handler.exit_code = 1;
}
drain(self);
if handled {
return;
}
return;
return true;
}
Mode::Strict => {
let wrapped = unhandled_rejection_as_uncaught_error(global_object, reason);
Expand All @@ -4420,29 +4412,27 @@ impl VirtualMachine {
if !handled {
emit_warning(self);
}
drain(self);
return;
return true;
}
Mode::Throw => {
if handle_unhandled() {
drain(self);
return;
return true;
}
let wrapped = unhandled_rejection_as_uncaught_error(global_object, reason);
if self.uncaught_exception(global_object, wrapped, true) {
drain(self);
return;
return true;
}
// continue to default handler — but RETURN if this drain
// errors (the VM is dead; don't bump the counter or invoke the
// handler).
if self.event_loop_mut().drain_microtasks().is_err() {
return;
return false;
}
}
}
self.unhandled_error_counter += 1;
(self.on_unhandled_rejection)(self, global_object, reason);
false
}

/// After a hot reload, surfaces the entry-point promise's rejection (if any) and re-arms the watcher.
Expand Down
15 changes: 10 additions & 5 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3349,16 +3349,17 @@ RefPtr<Performance> GlobalObject::performance()
return m_performance;
}

extern "C" void Bun__handleRejectedPromise(Zig::GlobalObject* JSGlobalObject, JSC::JSPromise* promise, JSC::EncodedJSValue rejectionOwner);
extern "C" bool Bun__handleRejectedPromise(Zig::GlobalObject* JSGlobalObject, JSC::JSPromise* promise, JSC::EncodedJSValue rejectionOwner);

void GlobalObject::handleRejectedPromises()
bool GlobalObject::handleRejectedPromises()
{
if (m_aboutToBeNotifiedRejectedPromises.isEmpty()) [[likely]]
return;
return false;

JSC::VM& virtual_machine = vm();
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(virtual_machine);
do {
bool listenerRan = false;
// Move the whole list out under one cellLock, then iterate linearly —
// the same pattern JSC's VM::didExhaustMicrotaskQueue and WebCore's
// RejectedPromiseTracker use.
Expand All @@ -3373,17 +3374,21 @@ void GlobalObject::handleRejectedPromises()
// From here on a handler on this promise is late: promiseRejectionTracker(Handle) owes it 'rejectionHandled'.
m_aboutToBeNotifiedRejectedPromises.markReported(this, promise);

Bun__handleRejectedPromise(this, promise, JSValue::encode(rejectionOwners.at(i)));
listenerRan |= Bun__handleRejectedPromise(this, promise, JSValue::encode(rejectionOwners.at(i)));
if (auto ex = scope.exception()) {
if (virtual_machine.isTerminationException(ex)) [[unlikely]]
return;
return false;
(void)scope.tryClearException();
this->reportUncaughtExceptionAtEventLoop(this, ex);
}
}
// Node runs the listeners of the whole batch before the ticks and microtasks they queued.
if (listenerRan)
return true;
// An unhandledRejection handler may itself reject a promise; loop
// until the list stays empty.
} while (!m_aboutToBeNotifiedRejectedPromises.isEmpty());
return false;
}

DEFINE_VISIT_CHILDREN(GlobalObject);
Expand Down
4 changes: 3 additions & 1 deletion src/jsc/bindings/ZigGlobalObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,9 @@ class GlobalObject : public Bun::GlobalScope {

uint8_t drainMicrotasks();

void handleRejectedPromises();
bool hasRejectedPromises() const { return !m_aboutToBeNotifiedRejectedPromises.isEmpty(); }
// True when a process 'unhandledRejection' listener ran: run a microtask checkpoint, then call again.
bool handleRejectedPromises();
ALWAYS_INLINE void initGeneratedLazyClasses();

template<typename Visitor>
Expand Down
8 changes: 7 additions & 1 deletion src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4142,7 +4142,13 @@ JSC::EncodedJSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC::JSGlobalObjec
// Rust -> C++ boundary function).
__attribute__((__always_inline__)) JSC::VM* JSC__JSGlobalObject__vm(JSC::JSGlobalObject* arg0) { return &arg0->vm(); };

void JSC__JSGlobalObject__handleRejectedPromises(JSC::JSGlobalObject* arg0)
// One load and a compare, asked at the end of every loop turn. always_inline as JSC__JSGlobalObject__vm above.
__attribute__((__always_inline__)) bool JSC__JSGlobalObject__hasRejectedPromises(JSC::JSGlobalObject* arg0)
{
return uncheckedDowncast<Zig::GlobalObject>(arg0)->hasRejectedPromises();
}

bool JSC__JSGlobalObject__handleRejectedPromises(JSC::JSGlobalObject* arg0)
{
return uncheckedDowncast<Zig::GlobalObject>(arg0)->handleRejectedPromises();
}
Expand Down
3 changes: 2 additions & 1 deletion src/jsc/bindings/headers.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions src/jsc/virtual_machine_exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,21 @@ pub fn handle_rejected_promise(
global: &JSGlobalObject,
promise: &mut JSPromise,
rejection_owner: JSValue,
) {
) -> bool {
crate::mark_binding!();

let result = promise.result(global.vm());
let jsc_vm = global.bun_vm().as_mut();

// this seems to happen in some cases when GC is running
if result.is_empty() {
return;
return false;
}

jsc_vm.unhandled_rejection_owned(global, result, promise.to_js(), rejection_owner);
let checkpoint_owed =
jsc_vm.unhandled_rejection_owned(global, result, promise.to_js(), rejection_owner);
jsc_vm.auto_garbage_collect();
checkpoint_owed
}

/// `Bun__handleHandledPromise`'s hop to the next turn of the loop.
Expand Down
Loading
Loading