Sub topic 6
Handling Errors with try/catch/finally
This chapter assumes you already know how try/catch/finally works in synchronous JavaScript, what a rejected Promise is, how .catch() works on a Promise chain, and what await does to an async function. Here you will see how those pieces fit together: a rejection becomes an exception at the await, an exception becomes a rejection when it leaves the async function, and a few details decide whether your catch block runs at all.
The core rule: rejection becomes a throw
When the Promise you await rejects, the await expression throws the rejection reason, just as if a throw statement sat at that spot. Code after the await in the same block does not run, and control jumps to the nearest enclosing catch.
The rule also works in reverse. If an exception leaves an async function without being caught, the function does not throw to its caller. It returns a Promise that rejects with that exception.
const failLater = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function step() {
console.log('before await');
await failLater(100, 'step failed');
console.log('never printed');
}
async function main() {
try {
await step();
} catch (err) {
console.log('caught:', err.message);
}
}
main();
// before await
// caught: step failedThe error crosses two async boundaries here. failLater rejects, the await inside step throws, step's returned Promise rejects, and the await inside main throws again, where the catch finally handles it. Each await turns a rejection back into a throw, so errors move up through awaited calls the same way they move up a synchronous call stack.
Synchronous throws inside async functions also reject
Any exception inside an async function becomes a rejection, and that includes exceptions from ordinary synchronous code. A JSON.parse failure or a TypeError from reading a property of undefined does not throw at the call site. It shows up as a rejected Promise.
async function parseConfig(text) {
return JSON.parse(text); // throws SyntaxError on bad input
}
const result = parseConfig('{not json');
console.log('call returned normally:', result instanceof Promise); // true
result.catch(err => console.log('rejected with:', err.name)); // SyntaxErrorSo a try/catch around a call to an async function that is not awaited catches nothing. The function has already returned its Promise without throwing.
A realistic example: fetch and HTTP errors
fetch rejects only when the request cannot complete at all, for example because of a DNS failure, a dropped connection, or a CORS block. A 404 or 500 response is a successful fetch in that sense, and the Promise fulfills with a Response whose ok property is false. If you want HTTP errors to reach your catch block, throw them yourself.
async function loadUser(id) {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (err) {
console.error('Failed to load user:', err);
throw err;
} finally {
console.log('loadUser finished');
}
}This one catch block handles three kinds of failure:
| Failure | Where it starts | How it reaches `catch` |
|---|---|---|
| Network error | `fetch` rejects | The first `await` throws |
| Non-OK status | Your `if` check | Your `throw` statement |
| Malformed JSON body | `response.json()` rejects | The second `await` throws |
The catch block logs the error and then rethrows it. That decision matters. If you log and do not rethrow, loadUser fulfills with undefined, and the caller cannot tell that anything went wrong. Catch an error only where you can do something useful with it: recover, retry, supply a default, or add context. Otherwise, let it propagate.
`return` versus `return await` inside try
This is the most common error-handling bug in async code. Inside a try block, return somePromise and return await somePromise behave differently.
const fail = () => Promise.reject(new Error('boom'));
async function withoutAwait() {
try {
return fail(); // the Promise is handed back unsettled
} catch (err) {
return 'caught inside';
}
}
async function withAwait() {
try {
return await fail(); // the rejection throws here, inside try
} catch (err) {
return 'caught inside';
}
}
withoutAwait().then(
value => console.log('withoutAwait value:', value),
err => console.log('withoutAwait escaped:', err.message) // runs
);
withAwait().then(
value => console.log('withAwait value:', value) // 'caught inside'
);In withoutAwait, return fail() leaves the try block right away with a pending Promise. The rejection happens later, after the function has exited the try, so the catch never sees it. The outer Promise simply adopts the rejection. In withAwait, the function stays inside the try until the Promise settles, so the rejection throws where the catch can handle it.
The same applies to finally. With plain return promise, the finally block runs before the operation finishes, which defeats cleanup such as hiding a spinner or releasing a lock.
What finally guarantees, and one trap
A finally block runs whether the try block completed, returned, or threw, and whether or not the catch block rethrew. In async code it runs after the awaited work inside try settles, so it is the right place for cleanup.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
let busy = false;
async function save(data) {
busy = true;
try {
await delay(100);
if (!data) throw new Error('nothing to save');
return 'saved';
} finally {
busy = false; // runs on success and on failure
console.log('busy reset');
}
}
save('x').then(console.log); // busy reset, saved
save(null).catch(err => console.log(err.message)); // busy reset, nothing to saveThe trap: a return statement (or a throw) inside finally replaces whatever the try or catch produced. That includes a pending exception.
async function swallowed() {
try {
throw new Error('real problem');
} finally {
return 'looks fine'; // discards the error
}
}
swallowed().then(v => console.log(v)); // 'looks fine'Keep finally limited to cleanup. Do not return from it, and if cleanup itself can fail, give it its own try/catch so a cleanup error does not hide the original one.
Adding context with error causes
When you rethrow, you often want to say what was being attempted without losing the original error. Since ES2022 (Node 16.9+, all current browsers), the Error constructor accepts a cause option.
async function readSettings() {
throw new Error('ENOENT: settings.json not found');
}
async function startApp() {
try {
await readSettings();
} catch (err) {
throw new Error('App startup failed', { cause: err });
}
}
startApp().catch(err => {
console.log(err.message); // App startup failed
console.log(err.cause.message); // ENOENT: settings.json not found
});Wrapping is better than string concatenation, because the original stack trace and error type stay available in err.cause for logging and for checks such as err.cause.name === 'AbortError'.
Choosing where to handle errors
Narrow try blocks
A large try block around many awaits makes it hard to know which step failed, and it can catch errors you meant to let through, including bugs in your own code. When different steps need different responses, give each step its own try, or handle one step inline.
Mixing await with .catch()
await works on any Promise, including one with a .catch() attached. This gives you a short way to provide a fallback for a single operation:
const failLater = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function loadDashboard() {
const prefs = await failLater(50, 'prefs unavailable')
.catch(() => ({ theme: 'light' })); // default on failure
console.log('theme:', prefs.theme); // theme: light
}
loadDashboard();This form keeps prefs as a const in the outer scope. A try/catch version would need a let declared before the try.
Handling at the top
Somewhere, every async call chain needs a final handler. That handler is usually a try/catch in the top-level async function, or a .catch() on its returned Promise:
async function main() {
throw new Error('unexpected');
}
main().catch(err => {
console.error('Fatal:', err.message);
process.exitCode = 1; // Node.js: signal failure without killing pending work
});Unhandled rejections
A rejected Promise that nothing handles is an unhandled rejection. Browsers log it to the console as "Uncaught (in promise)" and fire an unhandledrejection event on window. Since Node.js 15, an unhandled rejection terminates the process by default, the same way an uncaught exception does.
The usual cause is calling an async function without awaiting it or attaching .catch(). You can register global listeners (window.addEventListener('unhandledrejection', ...) in browsers, process.on('unhandledRejection', ...) in Node.js) for logging and crash reporting. Use them as a safety net. They are not a replacement for handling errors where they occur.
Summary of the rules
| Situation | Behavior |
|---|---|
| Awaited Promise rejects | `await` throws the reason |
| Exception leaves an async function | The function's Promise rejects |
| `return promise` inside `try` | Rejection bypasses `catch` and runs `finally` early |
| `return await promise` inside `try` | Rejection is caught, and `finally` waits |
| `return` inside `finally` | Overrides the result and swallows errors |
| `fetch` gets a 404 or 500 | Fulfills, so check `response.ok` and throw yourself |
| Nothing handles a rejection | Console warning in browsers, process exit in Node.js 15+ |
Exercise
A function contains try { return loadData(); } catch (e) { return []; } finally { console.log('done'); }, where loadData is an async function that rejects after 200 ms. What does a caller receive, and when does 'done' print? How do you fix it?
Show answer
The caller receives a Promise that rejects with loadData's error, because return loadData() leaves the try block before the rejection happens, so the catch never runs. 'done' prints right away, before loadData settles. Changing the line to return await loadData(); keeps execution inside the try until the Promise settles. The catch then runs and the function fulfills with [], and 'done' prints after the 200 ms.
Exercise
Why does wrapping try { saveAll(); } catch (e) { ... } fail to catch errors when saveAll is an async function, and what are two ways to fix it?
Show answer
Calling saveAll() without await returns a Promise immediately and never throws synchronously, so the catch block has nothing to catch, and the later rejection goes unhandled. Fix it by writing await saveAll(); inside the try (from an async function), or by attaching a handler directly with saveAll().catch(e => { ... }).
Exercise
An async function's try block throws an Error, its catch block rethrows it, and its finally block contains return 'ok'. What does the function's Promise settle to?
Show answer
It fulfills with 'ok'. A return inside finally replaces the pending exception, so the error is silently discarded. Remove the return from finally and limit finally to cleanup.