Sub topic 12
Unhandled Rejections and How to Catch Them
This chapter assumes you already know how then, catch and finally build chains, how errors travel through a chain, and how async/await works with try/catch. It also helps to know that promise callbacks run as microtasks, which the previous chapters covered.
A rejected promise holds an error. If no code ever reacts to that error, the error disappears silently unless the runtime notices it. This chapter explains how JavaScript runtimes detect such "unhandled" rejections, what they do about them, and how to write code that never produces them.
What "unhandled" means
A rejection is handled when the rejected promise has at least one rejection reaction attached. A rejection reaction is a catch callback, the second argument to then, or an await inside a try block. Each one subscribes to the promise's failure.
A rejection is unhandled when the promise rejects and, by the time the current batch of microtasks has finished, nothing has subscribed to its failure.
The key point is that "handled" is a property of each individual promise. Every call to then, catch or finally returns a new promise, and each of those new promises can be handled or unhandled independently.
const p = Promise.reject(new Error('lost'));
// p itself is handled: then() attached a reaction to it.
// But then() returns a NEW promise q, which also rejects
// (no rejection handler was given), and nobody handles q.
const q = p.then((v) => console.log(v));Running this in Node.js crashes the process, and the error comes from q, not from p. Adding a .then without a rejection handler does not handle anything. It moves the rejection one step down the chain.
How runtimes detect unhandled rejections
The runtime cannot know whether you will attach a handler later, so it waits for a short while before deciding. In practice the check runs after the microtask queue drains. Any handler attached synchronously, or in a microtask queued before the check, counts.
Because detection waits for the microtask queue to drain, this code is fine:
const p = Promise.reject(new Error('late but ok'));
queueMicrotask(() => {
p.catch((err) => console.log('caught:', err.message));
});
// caught: late but okBut attaching the handler in a timer is too late. Timers run as macrotasks, after the rejection check:
process.on('unhandledRejection', (reason) => {
console.log('unhandled:', reason.message);
});
process.on('rejectionHandled', () => {
console.log('handled after all');
});
const p = Promise.reject(new Error('too late'));
setTimeout(() => {
p.catch(() => {});
}, 0);
// unhandled: too late
// handled after allWhat Node.js does
Since Node.js 15, the default mode is --unhandled-rejections=throw. When a rejection goes unhandled, Node emits the unhandledRejection event on process. If no listener is registered for that event, Node raises the rejection as an uncaught exception, prints the error, and exits with code 1.
You can change this with a command-line flag:
| Mode | Behaviour |
|---|---|
| `throw` (default) | Emit `unhandledRejection`; if no listener, treat as an uncaught exception and crash |
| `strict` | Raise as an uncaught exception immediately; emit `unhandledRejection` only if the exception is caught by an `uncaughtException` handler |
| `warn` | Always print a warning, never crash |
| `warn-with-error-code` | Print a warning and set the exit code to 1, but keep running |
| `none` | Stay silent |
The two relevant process events are:
unhandledRejectionwith arguments(reason, promise), fired when a rejection is detected as unhandled.rejectionHandledwith argument(promise), fired when a handler is attached to a promise that was already reported.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
// Log to your monitoring service here, then exit deliberately.
process.exitCode = 1;
});
Promise.reject(new Error('nobody caught me'));What browsers do
Browsers never crash the page. They print an "Uncaught (in promise)" error to the console and fire an unhandledrejection event on window (or on self in workers). The event object has reason and promise properties. Calling event.preventDefault() stops the console message.
window.addEventListener('unhandledrejection', (event) => {
console.log('Reporting:', event.reason);
event.preventDefault(); // suppress the default console error
});
window.addEventListener('rejectionhandled', (event) => {
console.log('Handled late:', event.reason);
});
Promise.reject(new Error('browser example'));Error-tracking tools hook into this event to collect promise failures from real users.
Where unhandled rejections come from
The runtime hooks are a last line of defence. Most unhandled rejections come from a few habits.
Floating promises
A floating promise is one that is created and then dropped. No code stores it, returns it or awaits it. The usual cause is calling an async function without await:
async function save(record) {
throw new Error(`cannot save ${record.id}`);
}
async function handleRequest() {
try {
save({ id: 1 }); // missing await: the try block cannot see this rejection
} catch (err) {
console.log('never runs');
}
}
handleRequest();The try/catch only catches rejections that reach an await inside it. The fix is await save({ id: 1 }). If you really do mean fire-and-forget, attach a handler right where you make the call: save({ id: 1 }).catch(logError).
Forgotten returns inside then
If a then callback starts a promise but does not return it, the outer chain cannot see that promise's rejection:
function step() {
return Promise.reject(new Error('inner failure'));
}
Promise.resolve()
.then(() => {
step(); // not returned: rejection escapes the chain
})
.catch((err) => console.log('never reached'));Write return step(); or use a concise arrow () => step() so the chain adopts the inner promise.
Starting promises early, awaiting them late
Starting work first and awaiting later is a good way to get concurrency, but awaiting the promises one at a time leaves a gap:
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const failSoon = (ms) =>
new Promise((_, reject) => setTimeout(() => reject(new Error('fast fail')), ms));
async function main() {
const slow = delay(200, 'slow');
const fast = failSoon(50);
try {
await slow; // suspended here for 200 ms
await fast; // fast already rejected at 50 ms with no handler
} catch (err) {
console.log('caught:', err.message);
}
}
main();In Node.js, fast rejects at 50 ms. At that moment main is still suspended on slow, so nothing has subscribed to fast and the process crashes before the catch can run. Use Promise.all([slow, fast]) instead. Promise.all attaches handlers to every input as soon as it is called.
Rethrowing without an outer handler
A catch that rethrows, or a finally that throws, produces a new rejected promise. If that promise is the end of the chain, the rejection is unhandled again:
Promise.reject(new Error('original'))
.catch((err) => {
console.log('logging', err.message);
throw err; // rethrown: the promise returned by catch rejects
});
// Node.js: crashes with "original"Rethrowing is correct when a caller further up handles the error. Make sure that caller exists.
Combinators and handled rejections
The combinators subscribe to every promise you pass them, so their inputs count as handled:
Promise.allrejects with the first rejection. Later rejections from the other inputs are absorbed quietly and never reported.Promise.allSettlednever rejects. Every failure becomes a{ status: 'rejected', reason }entry.Promise.raceandPromise.anyalso subscribe to all inputs.Promise.anyrejects with anAggregateErroronly when every input rejects.
The promise a combinator returns still needs its own handler. Promise.all([...]) with no catch and no await is a floating promise.
A checklist for rejection-safe code
- Every promise is returned, awaited, passed to a combinator, or given a
.catchat the point where you create it. - Every chain ends in a
catch, or is returned to a caller that handles it. - In
asyncfunctions, promises you start early are awaited together withPromise.allorPromise.allSettled. - Top-level entry points (
main(), event handlers, route handlers) catch errors themselves. - A process-level
unhandledRejectionlistener (or a browserunhandledrejectionlistener) reports anything that slips through.
Linters can enforce the first rule. The TypeScript ESLint rule @typescript-eslint/no-floating-promises flags promises that are neither awaited nor handled.
Exercise
In Node.js 20 with default settings, does this program crash? Explain why or why not. const p = Promise.reject(new Error('x')); const handled = p.then(() => 'ok', (e) => 'recovered'); handled.then((v) => console.log(v));
Show answer
It does not crash, and it logs "recovered". The second argument to then is a rejection handler, so p is handled. The promise returned by that then fulfills with "recovered", so handled never rejects and the last then has nothing to handle.
Exercise
A teammate writes items.forEach(async (item) => { await upload(item); }); inside a try/catch, and one upload rejects. Why does the catch block not run, and how would you rewrite it so failures are caught?
Show answer
forEach ignores the promises returned by the async callback, so each one floats. The try/catch finishes before any upload settles, and a rejecting upload becomes an unhandled rejection. Rewrite it as await Promise.all(items.map((item) => upload(item))); inside the try block, or use a for...of loop with await if the uploads must run one after another.
Exercise
Why does attaching .catch inside setTimeout(..., 0) still trigger an unhandledRejection event, while attaching it inside queueMicrotask does not?
Show answer
The runtime checks for unhandled rejections after the microtask queue drains. A callback queued with queueMicrotask runs before that check, so the handler is attached in time. A setTimeout callback is a macrotask that runs after the check, so the rejection has already been reported. Attaching the handler later fires rejectionHandled.