Sub topic 11
Promise Rejections and .catch()
This chapter assumes you can create and chain promises with new Promise, .then(), and Promise.resolve(). It also assumes you have read the earlier chapters on try/catch and on why try/catch misses errors in callbacks that run later. All examples run in Node.js 18 or later, or in a browser console.
The previous chapter showed that a try block has already finished by the time a later callback runs. Promises solve this by carrying the failure forward. A promise ends in one of two states. It is fulfilled with a value, or it is rejected with a reason. A rejection is the asynchronous version of a thrown error. It moves down the promise chain until a rejection handler takes it.
How a Promise Becomes Rejected
A promise can be rejected in three ways:
- The executor function calls
reject(reason). - The executor function throws synchronously.
- A
.then()callback throws, or returns a promise that rejects. The promise returned by that.then()is then rejected.
function parseNumber(text) {
return new Promise((resolve, reject) => {
const n = Number(text);
if (Number.isNaN(n)) {
reject(new TypeError(`Not a number: ${text}`));
} else {
resolve(n);
}
});
}
parseNumber('42').then((n) => console.log('Parsed', n)); // Parsed 42
parseNumber('abc').catch((err) => console.log(err.name, err.message));
// TypeError Not a number: abc
// A synchronous throw inside the executor also rejects the promise
new Promise(() => {
throw new RangeError('thrown in executor');
}).catch((err) => console.log('Caught:', err.message)); // Caught: thrown in executorThe promise constructor wraps the executor in its own try/catch. That is why a synchronous throw becomes a rejection. The protection covers only the executor's synchronous run. If the executor schedules a timer and the timer callback throws, the error escapes the promise completely:
// Do not do this: the throw happens after the executor returned
new Promise(() => {
setTimeout(() => {
throw new Error('escapes the promise');
}, 0);
}).catch(() => console.log('This never runs'));Inside asynchronous callbacks in an executor, call reject instead of throwing:
function delayedFailure(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`failed after ${ms} ms`)), ms);
});
}
delayedFailure(10).catch((err) => console.log(err.message)); // failed after 10 msWhat .catch() Really Is
.catch(onRejected) is shorthand for .then(undefined, onRejected). It registers a callback that runs only if the promise it is attached to rejects. Like .then(), it returns a new promise. The state of that new promise depends on what the handler does:
| Handler behavior | Promise returned by `.catch()` |
|---|---|
| Returns a value (or nothing) | Fulfilled with that value (or `undefined`) |
| Returns a promise | Follows that promise |
| Throws an error | Rejected with that error |
| Never runs because the input fulfilled | Fulfilled with the same value as the input |
The first row matters most. A .catch() that returns normally marks the failure as recovered, and the chain continues on its success path.
Promise.reject(new Error('cache miss'))
.catch((err) => {
console.log('Recovering from:', err.message);
return { items: [] }; // fallback value
})
.then((data) => console.log('Continuing with', data));
// Recovering from: cache miss
// Continuing with { items: [] }How Rejections Travel Down a Chain
When a promise rejects, every following .then() success callback is skipped. The rejection passes along until it reaches a rejection handler. This lets a single .catch() at the end cover every step before it:
fetch('/api/items')
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((items) => console.log(items))
.catch((err) => console.error('Request failed:', err.message));A network failure rejects the fetch promise. A bad HTTP status throws in the first callback. Invalid JSON rejects res.json(). All three end up in the same .catch(). fetch does not reject on 404 or 500 responses, so the explicit res.ok check turns those into rejections.
Placement decides what a handler covers
A .catch() handles rejections from everything above it in the chain. It does not cover anything below it. Placing a .catch() in the middle gives you local recovery:
function getPrice(id) {
return id === 2
? Promise.reject(new Error(`no price for ${id}`))
: Promise.resolve(id * 10);
}
getPrice(2)
.catch(() => 0) // recover only the price lookup
.then((price) => {
if (price === 0) throw new Error('Free items are not allowed');
return price;
})
.then((price) => console.log('Price:', price))
.catch((err) => console.log('Order failed:', err.message));
// Order failed: Free items are not allowedThe first .catch() turns the missing price into 0. The later throw happens below that handler, so only the final .catch() can see it.
then(onOk, onFail) is not the same as then(onOk).catch(onFail)
The two-argument form of .then() is a common trap. Its rejection handler covers only the promise that .then() is attached to. It does not cover the success callback next to it:
const ok = Promise.resolve('data');
ok.then(
() => { throw new Error('bug in success handler'); },
(err) => console.log('Two-arg handler:', err.message) // does NOT run
); // this error becomes an unhandled rejection
ok.then(() => { throw new Error('bug in success handler'); })
.catch((err) => console.log('Chained catch:', err.message));
// Chained catch: bug in success handlerUse the two-argument form only when you want different handling for "the input failed" and "my processing failed". In other cases, chain .catch().
Rethrowing Inside .catch()
The narrowing pattern from the instanceof chapter works the same way in promise handlers. Handle the errors you understand and throw the others again. A throw inside .catch() rejects the promise that .catch() returns, so the next handler down the chain receives the error.
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
}
}
function findUser(id) {
if (id === 0) return Promise.reject(new TypeError('id must be positive'));
return Promise.reject(new NotFoundError(`user ${id} not found`));
}
function findUserOrGuest(id) {
return findUser(id).catch((err) => {
if (err instanceof NotFoundError) return { name: 'guest' };
throw err; // not ours to handle
});
}
findUserOrGuest(7).then((u) => console.log(u.name)); // guest
findUserOrGuest(0).catch((err) => console.log('Caller sees:', err.message));
// Caller sees: id must be positivePromise finally()
.finally(callback) runs the callback whether the promise fulfilled or rejected. It works like the finally block, with a few promise-specific rules:
- The callback receives no arguments, so it cannot tell success from failure.
- Normally the original value or rejection passes through unchanged. A return value from the callback is ignored.
- If the callback throws or returns a rejected promise, that new error replaces the original outcome.
let loading = true;
Promise.reject(new Error('timeout'))
.finally(() => {
loading = false; // cleanup only
return 'ignored';
})
.catch((err) => console.log(err.message, '| loading =', loading));
// timeout | loading = falseCombinators and Rejection
Promise combinators each treat rejection differently. Choose one based on what a single failure should mean for the whole operation.
| Combinator | Rejects when | Rejection reason |
|---|---|---|
| `Promise.all` | Any input rejects | The first rejection reason |
| `Promise.allSettled` | Never | Not applicable. You get `{ status, value }` or `{ status, reason }` for each input |
| `Promise.race` | The first input to settle rejects | That reason |
| `Promise.any` | Every input rejects | An `AggregateError` whose `errors` array holds every reason |
const jobs = [
Promise.resolve('a'),
Promise.reject(new Error('b failed')),
Promise.resolve('c'),
];
Promise.all(jobs).catch((err) => console.log('all:', err.message));
// all: b failed
Promise.allSettled(jobs).then((results) =>
results.forEach((r) =>
console.log(r.status, r.status === 'fulfilled' ? r.value : r.reason.message)
)
);
// fulfilled a / rejected b failed / fulfilled c
Promise.any([Promise.reject(new Error('x')), Promise.reject(new Error('y'))])
.catch((err) => console.log(err.name, err.errors.map((e) => e.message)));
// AggregateError [ 'x', 'y' ]The Forgotten return
A promise that a .then() callback creates but does not return is disconnected from the chain. Its rejection skips your .catch() and becomes an unhandled rejection:
function step() {
return Promise.reject(new Error('step failed'));
}
// Broken: the inner promise is not returned
Promise.resolve()
.then(() => { step(); })
.catch(() => console.log('never runs'));
// Fixed: return it so the chain waits for it and sees its rejection
Promise.resolve()
.then(() => step())
.catch((err) => console.log('Caught:', err.message)); // Caught: step failedWhen a callback has a block body { ... }, check that it returns the promise it creates.
Unhandled Rejections
If a promise rejects and no handler is attached by the time the current microtask queue drains, the runtime reports an unhandled rejection. Browsers log it in the console. Since Node.js 15, an unhandled rejection crashes the process by default. Attaching a handler later still works, but the warning has already been printed. Every chain therefore needs a handler at its end, or it must be returned to a caller that handles it. The last-resort global handlers for these cases are covered in a later chapter.
Exercise
What does this code log, and why? Promise.reject(new Error('A')).then(() => console.log('then 1')).catch((e) => { console.log('catch', e.message); return 'B'; }).then((v) => console.log('then 2', v));
Show answer
It logs "catch A" and then "then 2 B". The rejection skips the first success callback and reaches .catch(). The handler returns 'B' normally, so the promise from .catch() fulfills with 'B' and the last .then() runs.
Exercise
A teammate writes promise.then(render, showError). Errors thrown inside render are not being shown. Explain the cause and give the fix.
Show answer
The second argument of .then() handles only rejections of promise itself. It does not cover errors thrown by render, which is in the same .then() call. Use promise.then(render).catch(showError), so that showError handles rejections from both the original promise and render.
Exercise
You load five optional widgets in parallel. The page must render whichever ones succeed and log the ones that fail. Which combinator should you use, and why not Promise.all?
Show answer
Use Promise.allSettled. It never rejects and reports a status for each input, so you can render the fulfilled results and log each rejection reason. Promise.all rejects on the first failure and discards the other results, so one broken widget would stop the whole page from rendering.