Error Handling with try and catch
await turns a rejection back into a thrown error, which is what lets ordinary try and catch work on asynchronous code.
A rejected promise that is awaited throws at that line, so try/catch handles async failures the same way it handles synchronous ones. What it cannot catch is a promise nobody awaited, which is where most real unhandled rejections come from.
EXERCISE
1try and catch Around an await
The reason async code can use ordinary error handling is that await converts a rejection into a throw.
The basic shape:
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
} catch (err) {
console.log("failed to load user:", err.message);
return null;
}
}
Both awaits are covered by one try. If either promise rejects, await throws at that line and control jumps to the catch, exactly as it would for a synchronous error.
Which means synchronous and asynchronous failures land in the same place:
async function process(id) {
try {
const user = await fetchUser(id); // async failure
return user.profile.name; // synchronous TypeError if profile is null
} catch (err) {
console.log("something failed:", err.message);
}
}
One catch covers a network failure and a null-property read. That unification is not available in a .then chain, where a .catch only sees the links placed before it. That unification is the main practical advantage of async/await over .then chains, where a .catch only covers the links before it.
finally works too, and runs either way:
async function loadUser(id) {
setLoading(true);
try {
return await fetch(`/api/users/${id}`).then((r) => r.json());
} catch (err) {
showError(err);
return null;
} finally {
setLoading(false);
}
}
One detail worth knowing: return versus return await.
// Without await: the promise is returned, and this try/catch
// has already exited by the time it rejects.
async function a() {
try {
return fetchUser(); // rejection NOT caught here
} catch (err) {
console.log("never runs");
}
}
// With await: the rejection happens inside the try.
async function b() {
try {
return await fetchUser(); // rejection IS caught
} catch (err) {
console.log("caught");
return null;
}
}
Outside a try, return await is redundant and costs two microtask turns. Inside one it is essential. This is a genuine, commonly-missed distinction, and linters flag the redundant case while often missing the necessary one.
Pro Tip: Put the
tryaround the smallest region you can actually recover from, not around the whole function body. Acatchwrapping twenty lines will happily swallow a typo as though it were a network failure, and you will spend an afternoon debugging a "flaky API" that was a misspelled property all along.
EXERCISE
2The Rejections try Cannot Catch
A promise nobody awaited fails on its own, outside any try block, and this accounts for most real unhandled rejections.
The shape that gets people:
async function run() {
try {
save(data); // not awaited
} catch (err) {
console.log("never runs");
}
}
save(data) returns a promise immediately, and the try block finishes before that promise has settled. When it later rejects, there is no try on the stack any more. The catch cannot help.
Adding one word fixes it:
try {
await save(data);
} catch (err) {
console.log("caught");
}
The same bug inside a loop, which is more common:
// Broken: forEach ignores the returned promise entirely
try {
items.forEach(async (item) => {
await process(item);
});
} catch (err) {
console.log("never runs, and the loop finished long ago");
}
// Working: a for...of loop awaits each turn
try {
for (const item of items) {
await process(item);
}
} catch (err) {
console.log("caught, and the loop stopped here");
}
forEach was designed before promises and discards whatever its callback returns. There is nothing for the try to wait for. Unit 5's pool example is the concurrent version of the same fix.
A detached promise inside an async callback is the hardest version to spot:
async function setUp() {
button.addEventListener("click", async () => {
await submitForm(); // rejects on its own, far from here
});
}
The listener is called by the browser, not by your code, so there is no caller to catch anything. The fix is a try inside the listener itself, because that is the only place with a stack:
button.addEventListener("click", async () => {
try {
await submitForm();
} catch (err) {
showError(err);
}
});
And the safety net that tells you when you missed one:
// Browser
window.addEventListener("unhandledrejection", (event) => {
console.log("unhandled:", event.reason);
event.preventDefault();
});
// Node
process.on("unhandledRejection", (reason) => {
console.log("unhandled:", reason);
});
This is for reporting, not for handling. A rejection reaching it is a bug you want to know about, and in modern an unhandled rejection terminates the process by default.
Pro Tip: The rule that catches nearly all of these: every promise should either be awaited, returned, or given a
.catch. If a call site does none of the three, the failure has nowhere to go. Scanning for bare async calls on their own line is a quick and surprisingly productive review habit.
EXERCISE
3Recovering, Retrying, or Giving Up
Catching an error is the easy half; deciding what should happen next is the part that needs thought.
Once you have caught a failure, you have four options, and picking the wrong one causes more damage than not catching it at all.
Return a fallback, when a sensible default exists:
async function getSettings(userId) {
try {
return await fetchSettings(userId);
} catch {
return DEFAULT_SETTINGS;
}
}
The caller gets working settings and never knows there was a problem. Correct when the default is genuinely acceptable, wrong when it silently hides that the user's real preferences were lost.
Retry, when the failure is likely to be temporary:
async function fetchWithRetry(url, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
return await fetch(url);
} catch (err) {
if (i === attempts - 1) throw err;
await delay(2 ** i * 1000); // 1s, 2s, 4s
}
}
}
The final attempt rethrows rather than swallowing. Backoff matters: retrying immediately three times against a struggling makes things worse, not better.
Only retry things that are safe to repeat. A read is safe. A payment is not, unless the supports an idempotency key.
Rethrow with context, when you cannot handle it but can explain it:
async function loadDashboard(userId) {
try {
return await fetchDashboard(userId);
} catch (err) {
throw new Error(`dashboard failed for user ${userId}`, { cause: err });
}
}
{ cause: err } keeps the original error attached, so nothing is lost. Unit 9 covers this properly. The caller now knows which user failed, which the raw network error did not say.
And the one to avoid: catching and doing nothing.
try {
await save(data);
} catch (err) {
// silence
}
The save failed, the user was told nothing, and no log records it. This is worse than an unhandled rejection, which would at least appear in a console. If you genuinely mean to ignore a failure, say so:
try {
await trackAnalytics(event);
} catch {
// Analytics is best-effort. A failure here must never block the user.
}
Same code, and the comment turns an apparent oversight into a decision the next reader can evaluate.
Pro Tip: Ask what the user should experience, not what the code should do. If they should see something different, the catch belongs where you can show it. If nothing should change for them, the catch belongs where the work started and should still log. A catch placed for neither reason is usually one that is hiding a bug.
