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/finally around one or more awaits. Use finally for 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.
  • .catch on a single call for a quick fallback: const data = await load().catch(() => defaultData);
  • Check response.ok with fetch: fetch only rejects on network failure, not on HTTP 404 or 500. Throw yourself when !response.ok.
  • Promise.allSettled when 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 with instanceof.

Things that are not caught

  • Promises you did not await (fire-and-forget). Their rejection escapes the try. 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}
8
9// Simulated fetch that can fail at the HTTP level
10async 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}
15
16async 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}
21
22async 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 original
30 } finally {
31 loading = false; // always runs
32 console.log("loading:", loading);
33 }
34}
35
36console.log(await showProfile("/api/me")); // Hello Ada
37console.log(await showProfile("/api/missing")); // Profile not found
38
39// Quick fallback for a single call
40const 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.

Open in study app