Sub topic 7
How Errors Travel Through a Chain
This chapter assumes you know how to build a chain with then, and that each then returns a new promise that settles with whatever its handler returns.
The rule: rejection skips forward
A rejection can start in two ways: a handler throws an error, or a handler returns a rejected promise. Either way, the promise returned by that then is rejected. Each promise further down the chain is then rejected with the same reason, and no fulfillment handler runs along the way. The rejection stops at the first rejection handler, which is usually a catch.
Promise.resolve()
.then(() => {
throw new Error('boom');
})
.then(() => console.log('skipped'))
.catch((err) => {
console.log('caught:', err.message); // caught: boom
return 'recovered';
})
.then((v) => console.log(v)) // recovered
.finally(() => console.log('cleanup')); // cleanupThe catch above returns a normal value, so the promise it returns is fulfilled with 'recovered'. The chain then carries on as a success chain. This works like try/catch in synchronous code: once you catch an error and do not rethrow it, execution continues normally after the catch.
Rethrowing to keep the chain rejected
Sometimes a step needs to react to an error without handling it, for example to log it. In that case, throw the error again from the catch. The chain stays rejected, and a later handler gets the same error.
function loadConfig() {
return Promise.reject(new Error('file missing'));
}
loadConfig()
.catch((err) => {
console.log('logging:', err.message); // logging: file missing
throw err;
})
.then(() => console.log('not reached'))
.catch((err) => console.log('final handler:', err.message)); // final handler: file missingcatch versus the second argument to then
then(onFulfilled, onRejected) takes an optional rejection handler as its second argument. That handler only sees rejections from earlier in the chain. It never sees errors thrown by the onFulfilled handler passed in the same call.
Promise.resolve('data')
.then(
(v) => { throw new Error('bad ' + v); },
() => console.log('never sees the error above')
)
.catch((err) => console.log('catch sees:', err.message)); // catch sees: bad datacatch(fn) is shorthand for then(undefined, fn). A catch placed after a step covers that step and everything before it, which is usually what you want.
| Handler | Catches errors from earlier steps | Catches errors from the success handler in the same call |
|---|---|---|
| `.then(ok, fail)` | Yes | No |
| `.then(ok).catch(fail)` | Yes | Yes |
finally passes the outcome through
finally runs its callback whether the promise was fulfilled or rejected. The callback gets no arguments, and its return value is ignored. The original value or error passes on to the next step unchanged. The one exception is when the finally callback throws or returns a rejected promise. Then that new rejection replaces the original outcome.
Promise.reject(new Error('timeout'))
.finally(() => {
console.log('closing connection');
return 'ignored';
})
.catch((err) => console.log(err.message));
// closing connection
// timeoutCommon errors
- Placing
catchtoo early. Errors thrown in later steps are not covered. Put a finalcatchat the end of the chain. - Throwing strings.
throw 'oops'loses the stack trace. ThrowErrorobjects instead. - Forgetting to return a promise inside
then. If you start a promise inside a handler and do not return it, its rejection is cut off from the chain and the chain'scatchnever sees it.
Exercise
What does this code log, and in what order? Promise.resolve(1).then((n) => { if (n < 5) throw new Error('small'); return n; }).then((n) => console.log('value', n)).catch((e) => { console.log('error', e.message); return 0; }).finally(() => console.log('done')).then((n) => console.log('final', n));
Show answer
It logs "error small", then "done", then "final 0". The first then throws because 1 < 5, so the "value" handler is skipped. The catch logs the message and returns 0, which makes the chain fulfilled again. finally runs and passes 0 through unchanged, so the last then logs "final 0".
Exercise
You want to log every failure in a fetchUser step but still let the caller's catch handle it. What should your catch do after logging?
Show answer
Throw the error again with throw err or return Promise.reject(err). If it returns normally, the chain becomes fulfilled and the caller's catch never runs.