Sub topic 11
Promise Rejections and .catch()
This chapter assumes you can create and chain promises with .then(), and that you have read the previous chapter on why try/catch cannot see errors thrown in callbacks that run later. All examples run as-is in Node.js or a browser console.
How a promise fails
A promise is always in one of three states: pending, fulfilled, or rejected. When a promise is rejected, it carries a reason, which is usually an Error object. A promise becomes rejected in any of these ways:
- The executor calls
reject(err). - The executor throws.
- A
.then()callback throws, or returns a promise that rejects.
const p1 = new Promise((resolve, reject) => reject(new Error('rejected')));
const p2 = new Promise(() => { throw new Error('thrown in executor'); });
const p3 = Promise.resolve(1).then(() => { throw new Error('thrown in then'); });
for (const p of [p1, p2, p3]) {
p.catch((err) => console.log(err.message));
}All three log their message. Inside promise code, throw and reject produce the same outcome.
One .catch() for the whole chain
When a step rejects, the chain skips every .then() fulfillment handler after it until it reaches a rejection handler. This lets a single .catch() at the end handle a failure from any earlier step.
function fetchItems(ok) {
return new Promise((resolve, reject) => {
setTimeout(() => (ok ? resolve('["a","b"]') : reject(new Error('HTTP 500'))), 10);
});
}
fetchItems(false)
.then((text) => JSON.parse(text))
.then((items) => console.log('Items:', items)) // skipped
.catch((err) => console.error('Request failed:', err.message));
// Request failed: HTTP 500.catch(fn) is shorthand for .then(undefined, fn). It returns a new promise, so the chain continues after it.
What happens after .catch()
The value that .catch() produces decides the state of the promise it returns:
| Inside the catch handler | Resulting promise |
|---|---|
| Returns a value (or nothing) | Fulfilled with that value |
| Throws or returns a rejecting promise | Rejected |
Returning a value recovers from the failure. Rethrowing passes the error on to the next handler further down the chain:
Promise.reject(new Error('cache miss'))
.catch(() => 'default value') // recover
.then((v) => console.log('Got:', v)) // Got: default value
.then(() => { throw new TypeError('bad input'); })
.catch((err) => {
if (!(err instanceof RangeError)) throw err; // rethrow what we can't handle
})
.catch((err) => console.log('Outer:', err.name)); // Outer: TypeErrorCommon errors
Forgetting to return a promise
If a .then() callback starts async work and does not return its promise, the chain stops waiting for it. A rejection from that work never reaches your .catch().
Promise.resolve()
.then(() => {
Promise.reject(new Error('lost')); // missing return
})
.catch(() => console.log('never runs'));
// Node reports an unhandled rejection for 'lost'Add return in front of the inner promise and the .catch() handles it.
Using the second argument of .then()
.then(onOk, onErr) does not catch errors thrown inside onOk itself, because onErr only handles the promise that came before this .then().
Promise.resolve(1).then(
() => { throw new Error('in onOk'); },
() => console.log('not called')
); // unhandled rejectionPut a separate .catch() after the .then().
Rejections with no handler at all
A rejected promise that has no handler attached is an unhandled rejection. Browsers log it to the console. Since Node.js 15, an unhandled rejection crashes the process by default. Every chain should end in a .catch(), or be returned to a caller that handles it.
Exercise
What does this code log, and why? Promise.reject(new Error('x')).catch((e) => e.message).then((v) => console.log('then:', v)).catch(() => console.log('catch'));
Show answer
It logs "then: x". The first .catch() returns the string 'x' without throwing, so the promise it returns is fulfilled with 'x'. The .then() runs with that value, and the last .catch() never runs.
Exercise
A teammate writes getUser().then((u) => { saveUser(u); }).catch(handleError), where saveUser returns a promise. Sometimes saveUser fails and handleError is never called. What is the fix?
Show answer
The callback does not return the promise from saveUser, so the chain does not wait for it and its rejection is unhandled. Change the callback to (u) => saveUser(u) or add return saveUser(u).