JavaScriptMedium
How to handle errors in async/await?
Wrap awaited calls in try/catch (with finally for cleanup); a rejected promise makes await throw, so you handle async errors exactly like synchronous ones, and any error you do not catch rejects the async function's own promise.
Patterns
try/catch/finallyaround one or more awaits. Usefinallyfor cleanup (hide a loading spinner, release a lock).- Catch at the right level: handle errors where you can do something useful (show a message, retry, fall back). Otherwise let them propagate to a central handler.
.catchon a single call for a quick fallback:const data = await load().catch(() => defaultData);- Check
response.okwith fetch:fetchonly rejects on network failure, not on HTTP 404 or 500. Throw yourself when!response.ok. Promise.allSettledwhen several operations run together and you want every result, including failures.- Error causes (ES2022):
throw new Error("Failed to load profile", { cause: err })adds context without losing the original error. - Custom error classes (
class HttpError extends Error) so callers can branch withinstanceof.
Things that are not caught
- Promises you did not
await(fire-and-forget). Their rejection escapes thetry. Either await them or attach.catch. - Errors inside callbacks that run later (e.g. inside
setTimeout).
Last line of defence
Browsers fire unhandledrejection; Node has process.on("unhandledRejection"). Log there, but do not rely on it for normal flow.
Code example
js
1class HttpError extends Error {2 constructor(status, message) {3 super(message);4 this.name = "HttpError";5 this.status = status;6 }7}89// Simulated fetch that can fail at the HTTP level10async function fakeFetch(url) {11 await new Promise((r) => setTimeout(r, 10));12 if (url.includes("missing")) return { ok: false, status: 404, json: async () => ({}) };13 return { ok: true, status: 200, json: async () => ({ name: "Ada" }) };14}1516async function loadProfile(url) {17 const res = await fakeFetch(url);18 if (!res.ok) throw new HttpError(res.status, `Request failed: ${res.status}`);19 return res.json();20}2122async function showProfile(url) {23 let loading = true;24 try {25 const profile = await loadProfile(url);26 return `Hello ${profile.name}`;27 } catch (err) {28 if (err instanceof HttpError && err.status === 404) return "Profile not found";29 throw new Error("Could not show profile", { cause: err }); // add context, keep the original30 } finally {31 loading = false; // always runs32 console.log("loading:", loading);33 }34}3536console.log(await showProfile("/api/me")); // Hello Ada37console.log(await showProfile("/api/missing")); // Profile not found3839// Quick fallback for a single call40const settings = await loadProfile("/api/missing").catch(() => ({ name: "Guest" }));41console.log(settings.name); // Guest
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.