Sub topic 7
How Errors Travel Through a Chain
This chapter assumes you already know how to create promises, how then, catch and finally attach handlers, and how a value returned from then becomes the input of the next step. Here we follow the other path: what happens when something goes wrong. You will see how a rejection moves down a chain, where it stops, how to recover or rethrow, and which errors a promise cannot catch at all.
The Core Rule: Rejections Skip Fulfillment Handlers
Every then call returns a new promise. That new promise settles based on what its handler does:
| Handler behavior | State of the promise returned by `then`/`catch` |
|---|---|
| Returns a plain value | Fulfilled with that value |
| Returns a promise that fulfills | Fulfilled with that promise's value |
| Returns a promise that rejects | Rejected with that promise's reason |
| Throws an error | Rejected with the thrown error |
| No handler for this outcome | Same outcome as the previous promise, passed through unchanged |
The last row explains propagation. .then(onFulfilled) has no rejection handler, so a rejection passes straight through it to the next promise. This repeats until the rejection reaches a promise that has a rejection handler.
function step(name, shouldFail) {
return (input) => {
if (shouldFail) throw new Error(`${name} failed`);
console.log(`${name} ran with`, input);
return input + 1;
};
}
Promise.resolve(0)
.then(step('A'))
.then(step('B', true))
.then(step('C'))
.catch((err) => {
console.log('caught:', err.message);
return -1;
})
.then((v) => console.log('final:', v));
// A ran with 0
// caught: B failed
// final: -1Step C never runs. The error thrown in B turns B's promise into a rejected one, C's handler is skipped, and catch receives the error. Because catch returns -1 normally, the promise it returns is fulfilled, and the chain continues on the success path.
catch Is Just then With a Rejection Handler
p.catch(fn) behaves exactly like p.then(undefined, fn). No separate mechanism is involved. A handler only receives rejections from promises above it in the chain, never from promises below it.
That leads to a real difference between two forms that look alike:
const p = Promise.resolve('data');
// Form 1: second argument to then
p.then(
(v) => {
throw new Error('bug in success handler');
},
(err) => console.log('second argument saw:', err.message)
).catch((err) => console.log('catch saw:', err.message));
// Output: catch saw: bug in success handlerThe second argument to then is attached to p, and p fulfilled. The error was thrown by the success handler next to it, so the error lands in the promise that then returns. Only the following catch sees it.
Use then(onFulfilled, onRejected) when you specifically want to handle a failure of the previous step without also catching bugs in the current success handler. In most code a trailing .catch is what you want.
Where You Place catch Matters
A catch in the middle of a chain recovers there, and later steps run as though nothing failed. A catch at the end handles everything before it. Pick the position deliberately.
const getConfig = () => Promise.reject(new Error('config missing'));
const startServer = (config) => {
console.log('starting on port', config.port);
return config.port;
};
// Recover early: fall back to a default, then keep going
getConfig()
.catch(() => ({ port: 8080 }))
.then(startServer)
.then((port) => console.log('listening on', port))
.catch((err) => console.log('startup failed:', err.message));
// starting on port 8080
// listening on 8080The first catch turns a missing config into a default object. The final catch remains as a safety net for failures in startServer or later steps.
A common error is putting a recovering catch too early and returning nothing from it. The recovered value is then undefined, and the next step fails with a confusing TypeError such as "Cannot read properties of undefined", far from the real cause.
Rethrowing: Handle Some Errors, Pass the Rest On
Often a step can deal with one kind of failure and should leave the others alone. Inside a catch, throwing again (or returning a rejected promise) keeps the chain rejected.
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
}
}
function fetchUser(id) {
if (id === 1) return Promise.resolve({ id: 1, name: 'Ada' });
if (id === 2) return Promise.reject(new NotFoundError(`user ${id} not found`));
return Promise.reject(new Error('database offline'));
}
function loadUser(id) {
return fetchUser(id).catch((err) => {
if (err instanceof NotFoundError) {
return { id, name: 'Guest' }; // recover from this one case
}
throw err; // anything else is not ours to handle
});
}
loadUser(1).then((u) => console.log(u.name)); // Ada
loadUser(2).then((u) => console.log(u.name)); // Guest
loadUser(3).catch((err) => console.log('fatal:', err.message)); // fatal: database offlineRethrowing the original err keeps its stack trace. If you want to add context, wrap it rather than replace it: throw new Error('loading user failed', { cause: err }). The cause option works in all current browsers and in Node.js 16.9 and later.
finally Passes the Outcome Through
finally runs on both fulfillment and rejection. It takes no argument, and normally it does not change the outcome. The value or reason from above passes through it untouched, and whatever its handler returns is ignored.
Promise.resolve('value')
.finally(() => 'ignored')
.then((v) => console.log(v)); // valuePromise.reject(new Error('original'))
.finally(() => console.log('cleanup ran'))
.catch((err) => console.log(err.message)); // cleanup ran, then: originalThere is one exception. If the finally handler throws, or returns a promise that rejects, that new error replaces the original outcome:
Promise.reject(new Error('original'))
.finally(() => {
throw new Error('from finally');
})
.catch((err) => console.log(err.message)); // from finallyThe original error is lost here. Keep cleanup code simple, or give it its own try/catch if it can fail. If finally returns a promise that fulfills, the chain waits for it and then passes the original outcome through, which makes it useful for async cleanup like closing a connection.
Which Errors a Promise Can Catch
A chain only sees errors that happen inside its handlers or executor while they run, plus explicit reject calls. These cases trip people up.
Synchronous throws in the executor become rejections
const p = new Promise(() => {
throw new Error('executor blew up');
});
p.catch((err) => console.log('caught:', err.message)); // caught: executor blew upThrows inside a later callback escape the promise
If the executor starts a timer or a callback-based API, a throw inside that callback happens later on a different call stack. The promise never sees it. In Node.js it becomes an uncaught exception and crashes the process. In a browser it shows up as an uncaught error, and the promise stays pending forever.
// Broken: the throw happens outside the executor's stack
const broken = new Promise((resolve) => {
setTimeout(() => {
resolve(JSON.parse('{bad json'));
}, 10);
});
// Fixed: catch inside the callback and call reject
const fixed = new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(JSON.parse('{bad json'));
} catch (err) {
reject(err);
}
}, 10);
});
fixed.catch((err) => console.log('caught:', err.name)); // caught: SyntaxErrorRunning the broken version in Node.js ends the process with a SyntaxError. The safer design is to wrap only the callback API in a tiny promise and do the parsing in a then handler, where a throw is caught automatically. A later chapter covers this wrapping pattern.
Throws after settlement are swallowed
Once a promise is settled, its state cannot change, so a later throw in the executor is silently ignored:
new Promise((resolve) => {
resolve('first');
throw new Error('never seen');
}).then((v) => console.log(v)); // firstReject With Error Objects
You can reject with any value, for example reject('timeout') or reject(404). Avoid it. Strings and numbers have no stack trace, err.message is undefined, and instanceof checks like the one in loadUser cannot tell them apart. Always reject with an Error or a subclass of it. Code that receives errors from libraries you don't control should still be defensive: String(err?.message ?? err) is a safe way to log an unknown reason.
What Happens When Nothing Catches
If a rejection reaches the end of a chain with no handler, nothing in your code reacts to it. The runtime reports it as an unhandled rejection. Browsers log it to the console, and Node.js (version 15 and later) terminates the process by default. A later chapter covers how to detect these. For now, the rule is that every chain needs a final rejection handler, or must be returned to a caller who provides one.
Exercise
What does this code print, and why does step 'three' not appear? Promise.resolve(1) .then((n) => { console.log('one'); return n; }) .then(() => Promise.reject(new Error('two failed'))) .then(() => console.log('three')) .catch((err) => { console.log('caught', err.message); }) .then((v) => console.log('after', v));
Show answer
It prints "one", then "caught two failed", then "after undefined". The second handler returns a rejected promise, so the promise from that then is rejected. The third then has no rejection handler, so the rejection passes through it and 'three' is skipped. The catch handles the error but returns nothing, so the chain becomes fulfilled with undefined.
Exercise
A teammate writes fetchData().then(render, showError). When render throws because of a bug, no error message appears for the user. Explain why and give the fix.
Show answer
The showError handler is attached to the promise from fetchData(), which fulfilled, so it never sees errors thrown by render, the handler beside it. The error ends up in the promise returned by then, which has no handler. Fix it with fetchData().then(render).catch(showError), so the catch sits below render and receives its errors.
Exercise
What does this print? Promise.reject(new Error('A')).finally(() => Promise.reject(new Error('B'))).catch((e) => console.log(e.message));
Show answer
It prints "B". A finally handler normally passes the original outcome through, but when it returns a rejected promise (or throws), that rejection replaces the original one, and error A is lost.