Sub topic 6
Handling Errors with try/catch/finally
This chapter assumes you know basic try/catch/finally from synchronous JavaScript, how Promises reject, and how await pauses an async function. It covers what happens when an awaited Promise rejects, and how to handle that failure with the same tools you already use for synchronous errors.
A Rejection Becomes a Throw
When an awaited Promise rejects, await throws the rejection reason at that line. Code after the await does not run. Control jumps to the nearest catch block, just as it would for a throw statement.
const failLater = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function run() {
try {
console.log('before');
await failLater(500, 'server unavailable');
console.log('never printed');
} catch (err) {
console.log('caught:', err.message);
} finally {
console.log('cleanup');
}
}
run();
// before
// caught: server unavailable
// cleanupYou do not need a separate error mechanism for asynchronous code. One try block can wrap several await expressions, and a failure in any of them lands in the same catch.
A Realistic Example with fetch
fetch rejects only on network failures. An HTTP 404 or 500 still fulfills with a Response object. Check response.ok yourself and throw if it is false, so both kinds of failure reach the same catch.
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');
}
}There are three points to notice in loadUser:
throw errrethrows the error after logging it. Without the rethrow,loadUserwould fulfill withundefined, and callers would think the request succeeded.finallyruns whether the function returns or throws. Use it for cleanup such as hiding a spinner, clearing a timer, or releasing a lock.return await response.json()is deliberate. The next section explains why.
Why return await Matters Inside try
If you write return response.json() without await, the function returns the Promise straight away and leaves the try block. If that Promise rejects later, for example because the body is invalid JSON, your catch never sees the error. Adding await keeps execution inside the try until the Promise settles.
| Code inside `try` | Rejection caught by local `catch`? |
|---|---|
| `return await promise` | Yes |
| `return promise` | No, it goes to the caller |
| `await promise` (no return) | Yes |
Outside a try block, return await and return behave the same for error handling.
Handling Errors at the Call Site
An async function that throws returns a rejected Promise. The caller can handle it with try/catch inside another async function, or with .catch():
async function getConfig() {
throw new Error('config missing');
}
getConfig().catch(err => console.log('handled:', err.message));
// handled: config missingChoosing Where to Catch
Catch an error where you can do something useful with it. That might mean retrying, showing a message, or returning a fallback value. Low-level functions often just add context and rethrow. Top-level code, such as a route handler or a click listener, is usually where errors finally get handled.
Exercise
An async function contains try { return fetchData(); } catch (e) { return 'fallback'; }, and fetchData returns a Promise that rejects. What does the caller receive, and how do you make the function return 'fallback' instead?
Show answer
The caller receives a rejected Promise, because the function returns fetchData's Promise and leaves the try block before the rejection happens. The local catch never runs. Change the line to return await fetchData();. The await keeps execution inside try, so the rejection is caught and the function fulfills with 'fallback'.
Exercise
Why does the catch block in loadUser end with throw err instead of simply logging the error?
Show answer
If the catch block only logs, the error counts as handled, and loadUser fulfills with undefined. Callers would then treat a failed request as a success. Rethrowing passes the rejection up to the caller, which can decide how to respond.