...

/

Web Browsers and Unhandled Rejections

Web Browsers and Unhandled Rejections

Look at how web browsers track and detect unhandled rejections.

Unhandled rejection tracking for web browsers

Unhandled rejection tracking for web browsers is defined in the HTML specification. At the core of unhandled rejection tracking are two events that are emitted by the globalThis object:

  • unhandledrejection: This is emitted when a promise is rejected and no rejection handler is called within one turn of the event loop.

  • rejectionhandled: This is emitted when a promise is rejected and a rejection handler is called after one turn of the event loop.

These two events are designed to be used together to accurately detect unhandled promise rejections. Here’s an example showing when each event is triggered:

Press + to interact
const rejected = Promise.reject(new Error("Oops!"));
setTimeout(() => {
// "rejectionhandled" triggered here
rejected.catch(
reason => console.error(reason.message) // "Oops!"
);
}, 500);
// "unhandledrejection" triggered at this point

In this code, rejected is a rejected promise that has no rejection handler attached initially. The unhandledrejection event is emitted once the script task has been completed to let us know that a rejected promise exists without a rejection handler. The timer adds a rejection handler after a delay of 500 milliseconds, at which point the rejectionhandled event is emitted to let us know that a promise previously flagged as having an unhandled rejection has now been handled. That means we need to track the promises triggering these events in ...