Sub topic 12
Unhandled Rejections and How to Catch Them
This chapter assumes you know how catch handles errors in a chain and how async functions return promises. It also assumes you can run code in Node.js or a browser console.
What counts as unhandled
A rejection is unhandled when a promise rejects and nothing has attached a rejection handler to it by the time the current job and its microtasks finish. A rejection handler is a catch, the second argument to then, or an await inside a try block. The error has nowhere to go, so the runtime reports it.
Promise.reject(new Error('lost'));
// Node.js: the process crashes with "Error: lost"
// Browser: "Uncaught (in promise) Error: lost" in the consoleEach promise is tracked on its own. A catch at the end of one chain does nothing for a different promise that was created and then forgotten.
How each runtime reacts
| Runtime | Event | Default with no listener |
|---|---|---|
| Browser | `unhandledrejection` on `window` | Logs "Uncaught (in promise)" |
| Node.js 15+ | `unhandledRejection` on `process` | Throws, process exits with code 1 |
| Node.js 14 and older | `unhandledRejection` on `process` | Prints a warning and keeps running |
Where they come from
Most unhandled rejections come from one of three mistakes.
- Fire-and-forget calls. You call an
asyncfunction and neverawaitit or attach acatchto its result. - A missing
returninsidethen. The inner promise splits off from the chain, so the outercatchnever sees its error. - A chain with no final
catch. Every handler in it can throw, and nothing at the end catches the error.
async function save() {
throw new Error('disk full');
}
function onClickBroken() {
save(); // rejection escapes: nobody is listening
}
function onClickFixed() {
save().catch((err) => console.error('save failed:', err.message));
}
onClickFixed(); // save failed: disk fullGlobal safety nets
A global listener lets you log or report errors that slipped through. Treat it as a last line of defence. Don't use it as your main way to handle errors.
// Node.js
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
process.exitCode = 1; // still signal failure
});
Promise.reject(new Error('lost')); // logged instead of crashing// Browser
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled rejection:', event.reason);
event.preventDefault(); // suppress the default console error
});
Promise.reject(new Error('lost'));Handlers attached too late
The check runs after the microtask queue drains. A handler you attach later, for example inside setTimeout, comes too late. The rejection has already been reported, and in Node.js 15+ the process has already crashed. In browsers, attaching the handler late fires a rejectionhandled event. The fix is to attach handlers in the same synchronous block that creates the promise. You can also hand the promise straight to await or a combinator.
Promise.all attaches handlers to every input. So when a second input rejects after the first, that second rejection is not reported as unhandled. It is still silently ignored, though. Use Promise.allSettled if you need to see every failure.
Exercise
Which of these calls produces an unhandled rejection, and why? (a) async function f() { throw new Error('x'); } f(); (b) Promise.reject(new Error('y')).then(() => 1).catch(() => 2); (c) Promise.resolve().then(() => { Promise.reject(new Error('z')); });
Show answer
(a) and (c). In (a), nobody awaits or catches the promise returned by f(). In (b), the rejection skips the then and reaches the catch, so it is handled. In (c), the inner rejected promise is not returned, so it is not part of the chain and no handler ever sees it.
Exercise
You add process.on('unhandledRejection', (r) => console.log(r)) to a Node.js 20 server. What changes in behaviour, and what should you add?
Show answer
Unhandled rejections no longer crash the process. They are only logged, and the server keeps running in a possibly broken state. Set process.exitCode, or call process.exit(1) after reporting, so the failure stays visible and a supervisor can restart the server.