Sub topic 3
Promise Rejections and .catch()
This chapter assumes you know basic promises, async/await, and the try/catch behavior from the earlier chapters. As shown there, try/catch cannot catch errors thrown in callbacks that run later. Promises fix this by carrying the failure along with them.
Promise Rejections and .catch()
A promise either fulfills with a value or rejects with a reason. If a then callback throws, the promise returned by that then rejects. The rejection skips each later then until it reaches a .catch(). One .catch() at the end therefore covers every step before it.
function getItems(ok) {
return ok ? Promise.resolve(['a', 'b']) : Promise.reject(new Error('HTTP 500'));
}
getItems(false)
.then((items) => items.map((i) => i.toUpperCase()))
.then((items) => console.log(items))
.catch((err) => console.error('Request failed:', err.message)); // Request failed: HTTP 500try/catch with async and await
Inside an async function, await turns a rejection back into a thrown error, so ordinary try/catch works again. The cause option keeps the original error attached when you rethrow a clearer one.
async function loadUser(id) {
try {
const res = await fetch(`https://example.com/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
throw new Error(`Failed to load user ${id}`, { cause: err });
}
}
loadUser(1).catch((err) => console.error(err.message, '<-', err.cause.message));Use return await inside try. A plain return fetchSomething() hands back the promise without waiting for it, so its rejection gets past your catch.
Last-Resort Global Error Handlers
Global handlers log errors that nothing else caught. They are not a recovery tool.
// Node.js
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});In browsers, listen for the error and unhandledrejection events on window. After an uncaught exception in Node.js, the program's state is unknown, so log the error and exit.
Where to Catch, Log, or Let Errors Propagate
| Situation | Action |
|---|---|
| You can recover, for example with a default or a retry | Catch it here |
| You can add useful context | Wrap it with `cause` and rethrow |
| You cannot do anything useful with it | Let it propagate |
| It reached the top of the program | Log it once, in a global handler or at the entry point |
Avoid logging the same error and then rethrowing it at every layer. The logs fill with copies of one failure.
Exercise
An async function contains try { return fetchData(); } catch { return null; }, and fetchData() rejects. Does the function return null? Why or why not?
Show answer
No. Without await, the try block returns the pending promise right away, so the rejection happens after the try block has finished and the catch never runs. The caller receives a rejected promise. Writing return await fetchData(); fixes it.