SyntaxPilot
Courses/JavaScript/Lesson 28
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 28 of 40

Error handling in async code

queued

These are the notes for JavaScript episode 28. In episode 27 you invented async/await, so asynchronous code finally reads like a recipe. But real apps talk to payment gateways, restaurants and SMS services, and those fail all the time. Here one failed payment crashes the whole food delivery app: Node.js prints Error: Payment gateway down and the program exits, so "Serving the next customer..." never prints. You'll find out why (an unhandled rejection crashes the process) and then invent the tools that keep the app running: try/catch around await (or .catch at the call), return await inside try, Promise.allSettled so one closed restaurant doesn't blank the home page, a timeout built from Promise.race, retry with exponential backoff for a flaky OTP service, custom error classes with instanceof to tell a temporary failure from a bug, { cause } so the original error is never lost, and process.on("unhandledRejection") as the last safety net. Every output below is real Node.js output (node main.js, Node 24); timings in milliseconds will differ slightly on your machine. In stack traces the long folder path is shortened to main.js.

Builds on: try/catch/finally (episode 13), classes and extends (16), the event loop (24), callbacks (25), promises and Promise.all (26), async/await (27). Leads to: functional patterns and immutability (29).

The real-life idea: the restaurant manager

At table four, the card machine fails. One table, one small problem.

  • If nobody's job is to handle that, the cashier panics and the whole restaurant shuts its doors. Every table is thrown out, not just table four.
  • A real restaurant has a manager close to the problem, who says: "No problem, pay by UPI, or cash."
  • The failure stays at table four. Every other table keeps eating and never notices.
Restaurant JavaScript
The card machine failing a promise that rejects (fails with an error)
Nobody handles it, the restaurant shuts an unhandled rejection: Node.js stops the whole program
The manager standing near the table a catch placed close to the await
"Pay by UPI instead" the code inside catch: a fallback or a friendly message
Other tables keep eating the rest of the program keeps running

The rule of the day: fail small, never fail everything.

The problem: one failed payment crashes the whole app

wait(ms) is a promise that fulfils after ms milliseconds (a promise is an object standing for a value that will be ready later: pending, then fulfilled with a value or rejected with an error). pay talks to the payment gateway, waits 200 ms, and today the gateway is down, so it throws. placeOrder awaits pay. Half a second later we want to serve the next customer:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(200);
  throw new Error("Payment gateway down");
}
async function placeOrder() {
  const receipt = await pay(180);
  console.log("Paid:", receipt);
}
placeOrder();
setTimeout(() => console.log("Serving the next customer..."), 500);
main.js:4
  throw new Error("Payment gateway down");
        ^

Error: Payment gateway down
    at pay (main.js:4:9)
    at async placeOrder (main.js:7:19)

Node.js v24.22.2

Serving the next customer... never printed. One failed payment, and the whole program died.

Why? throw inside an async function rejects its promise. placeOrder awaited it, so placeOrder's own promise rejected too (the error travels up). And the line placeOrder(); ignores the promise it gets back: nobody, anywhere, was listening. A rejected promise that no code ever handles is an unhandled rejection. Since Node 15, an unhandled rejection crashes the process (the running program): Node prints the error with its stack trace (the list of function calls that led to the error, newest first), then its version, and stops.

When a program ends it hands the operating system a number, the exit code: 0 means "all fine", anything else means "something failed". Servers, CI pipelines (automatic build-and-test systems) and shell scripts read it. Run node main.js; echo "exit code: $?" and, after the same error, the terminal prints exit code: 1. On a server, that crash means every customer is kicked out, not just the one whose payment failed.

Fix 1: try/catch around await

Put a manager around the await:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(200);
  throw new Error("Payment gateway down");
}
async function placeOrder() {
  try {
    const receipt = await pay(180);
    console.log("Paid:", receipt);
  } catch (err) {
    console.log("Order failed:", err.message);
  }
}
placeOrder();
setTimeout(() => console.log("Serving the next customer..."), 500);
Order failed: Payment gateway down
Serving the next customer...
  • When the awaited promise rejects, await throws the error right on that line, as if it were normal code. So a plain try/catch catches it.
  • err is the rejection reason: the value the promise failed with, here an Error object. err.message is its text.
  • The failure stayed small and the program lived; echo $? now prints exit code: 0.

Fix 2: .catch at the call

The other way is .catch(fn) on the promise, right where you call it (.catch registers a function that runs if the promise rejects). Keep the first placeOrder (no try) and change only the call line to placeOrder().catch((err) => console.log("Order failed:", err.message));. The output is the same two lines: Order failed: Payment gateway down, then Serving the next customer....

The rule: every promise must end at a try/catch (with await) or a .catch, somewhere. Use try/catch inside async functions; use .catch at the top, where a normal line starts an async job. And finally { ... } after the catch runs either way: the place to hide a loading spinner.

Trap: return without await escapes the try

safePay wants a cash fallback. It looks perfect:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(200);
  throw new Error("Payment gateway down");
}
async function safePay(amount) {
  try {
    return pay(amount);
  } catch (err) {
    return "Paid in cash";
  }
}
safePay(180).then((r) => console.log("Result:", r));
main.js:4
  throw new Error("Payment gateway down");
        ^

Error: Payment gateway down
    at pay (main.js:4:9)

Node.js v24.22.2

Crash again, and the catch never ran. return pay(amount) hands back the promise immediately, while it's still pending. The try block is already finished when the promise rejects 200 ms later; nobody is waiting inside the try. The rejection passes out to safePay's caller, and a .then with only a success function doesn't handle it. (Even the stack trace is shorter: safePay had already returned.)

The fix is two words, return await. Now the function waits inside the try, so the rejection lands in the catch:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(200);
  throw new Error("Payment gateway down");
}
async function safePay(amount) {
  try {
    return await pay(amount);
  } catch (err) {
    return "Paid in cash";
  }
}
safePay(180).then((r) => console.log("Result:", r));
Result: Paid in cash

Inside a try, always return await. Outside a try, return promise and return await promise give the caller the same result.

One shop down: Promise.all fails fast

The home page loads three restaurant menus at once with Promise.all (episode 26: an array of promises in, one promise for the array of their values out). menu waits, and throws if the shop is closed. Today, Biryani House is closed:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function menu(shop, ms, ok = true) {
  await wait(ms);
  if (!ok) throw new Error(shop + " is closed");
  return shop + " menu";
}
async function home() {
  try {
    const jobs = [menu("Dosa Corner", 200), menu("Biryani House", 100, false), menu("Chai Point", 300)];
    const menus = await Promise.all(jobs);
    console.log(menus);
  } catch (err) {
    console.log("Home page failed:", err.message);
  }
}
home();
Home page failed: Biryani House is closed

The whole page is blank, even though Dosa Corner and Chai Point were fine. Promise.all is all or nothing: the moment one promise rejects, Promise.all rejects with that error and the good results are thrown away. This is failing fast (giving up at the first failure). It's right when you need every result, like a bill that needs both the customer and the order. For a home page, it's the wrong choice.

Promise.allSettled: show what you can

Promise.allSettled([...]) waits until every promise has settled (fulfilled or rejected) and never rejects itself. It gives back one report card per promise, in the same order: { status: "fulfilled", value } or { status: "rejected", reason } (reason is the error).

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function menu(shop, ms, ok = true) {
  await wait(ms);
  if (!ok) throw new Error(shop + " is closed");
  return shop + " menu";
}
async function home() {
  const jobs = [menu("Dosa Corner", 200), menu("Biryani House", 100, false), menu("Chai Point", 300)];
  const results = await Promise.allSettled(jobs);
  for (const r of results) {
    if (r.status === "fulfilled") console.log("show:", r.value);
    else console.log("skip:", r.reason.message);
  }
}
home();
show: Dosa Corner menu
skip: Biryani House is closed
show: Chai Point menu

Two out of three, and the page works. Promise.all = need every one. Promise.allSettled = show what you can. Two cousins you'll meet next: Promise.race settles like the first promise to settle (success or failure), and Promise.any takes the first success, rejecting only if all fail (with an AggregateError, an error holding the list of errors). All four are combinators: functions that combine several promises into one.

Too slow: promises have no time limit

Not an error at all: a restaurant that's just slow. track asks for the delivery status, and today it takes three seconds:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function track(order) {
  await wait(3000);
  return order + " is on the way";
}
async function main() {
  const start = Date.now();
  const status = await track("Order 42");
  console.log(status, "after", Date.now() - start, "ms");
}
main();
Order 42 is on the way after 3001 ms

Three seconds staring at a spinner. If their server hangs (stops answering without failing), it could be thirty seconds, or forever: a promise has no built-in time limit.

A timeout is a race

A timeout is a time limit after which you stop waiting and treat the job as failed. Race the real job against an alarm, a promise that rejects after ms milliseconds, using Promise.race. Job first? You get the status. Alarm first? You get a Timed out error and show a friendly message. When the race is over, clearTimeout(timer) in finally switches the alarm off (setTimeout returns a timer id; clearTimeout(id) cancels it).

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function track(order) {
  await wait(3000);
  return order + " is on the way";
}
function timeout(promise, ms) {
  let timer;
  const alarm = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error("Timed out after " + ms + " ms")), ms);
  });
  return Promise.race([promise, alarm]).finally(() => clearTimeout(timer));
}
const start = Date.now();
timeout(track("Order 42"), 1000)
  .then((status) => console.log(status))
  .catch((err) => console.log("Sorry:", err.message, "at", Date.now() - start, "ms"));
Sorry: Timed out after 1000 ms at 1002 ms
  • Here there's no async main: .then gets the status if the job wins, .catch gets the timeout error if the alarm wins.
  • The alarm only ever rejects, so its first parameter (resolve) is unused; _ is a common name for "not used".
  • A promise's .finally(fn) runs fn when it settles either way, like finally in try.
  • We gave up after one second, on our terms. The timeout doesn't stop track itself; we just stop waiting for it. (A real network call can also be cancelled, for example fetch(url, { signal: AbortSignal.timeout(1000) }).)

Why clearTimeout matters

Without clearTimeout, a fast job still leaves the alarm ticking, and Node won't exit while a timer is pending. We raced a 200 ms job against a 3000 ms alarm with no clearTimeout, and logged the time in process.on("exit", fn) (which runs fn just before Node exits): the job printed Order 42 is on the way at 205 ms, but the program printed program ended at 3004 ms. With the episode's timeout, the same run ended at 203 ms. On a busy server, thousands of forgotten alarms waste memory.

Flaky network: retry with backoff

When you phone someone and the line is busy, it's a short, temporary failure. You wait a minute and call again. Still busy? Wait two minutes, then four. And after a few tries you stop, instead of calling a hundred times.

On the phone In code
Line busy, may work next time a transient error (a temporary failure that can go away by itself)
Wait 1 min, then 2, then 4 retry with exponential backoff (the wait doubles each time)
Stop after a few tries max attempts, then give up and pass the error on

Why wait longer each time? An overloaded server gets worse if you hammer it with instant retries; backing off gives it room to recover.

sendOtp sends a login OTP (one-time password). The network is busy the first two times and works on the third:

let calls = 0;
async function sendOtp(name) {
  if (++calls < 3) throw new Error("Network busy (try " + calls + ")");
  return "OTP sent to " + name;
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function retry(job, times, delay) {
  for (let attempt = 1; attempt <= times; attempt++) {
    try {
      return await job();
    } catch (err) {
      console.log("attempt", attempt, "failed:", err.message);
      if (attempt === times) throw err;
      await wait(delay);
      delay = delay * 2;
    }
  }
}
retry(() => sendOtp("Asha"), 4, 200).then(console.log, (err) => console.log("Gave up:", err.message));
attempt 1 failed: Network busy (try 1)
attempt 2 failed: Network busy (try 2)
OTP sent to Asha
  • ++calls adds 1 to calls first and then gives the new value (so the first call compares 1 < 3). calls++ would give the old value, then add 1.
  • The last line passes two functions to .then: console.log for success, and a failure function that prints Gave up:. .then(onSuccess, onFailure) works like .then(...).catch(...) here.
  • job is a function that starts the work (() => sendOtp("Asha")), not a promise. A promise is a job already started; to try again you need something you can call again.
  • return await job(): the await keeps us inside the try (the trap from earlier), so a failure reaches the catch.
  • Rethrowing (throw err inside a catch) passes the error on. We do it on the last attempt, so the caller learns the job really failed. When we made sendOtp fail every time and logged Date.now() - start, the four attempts failed at 0, 202, 603 and 1405 ms (waits of 200, 400, 800), then Gave up: Network busy (try 4).

Only retry failures that can go away, like a busy network or a timeout. Never retry a payment blindly: the first try may have gone through, and the customer pays twice. (Real systems also add a little randomness to each wait, called jitter, so thousands of phones don't retry at the same moment.) To retry safely you need to know which kind of error you have.

Know the error: custom error classes and instanceof

A custom error class is your own kind of error, made with class ... extends Error (episode 16). name = "TimeoutError"; is a class field: a property written directly in the class body, given to every object the class makes, so each TimeoutError gets err.name === "TimeoutError". There's no constructor, so the one from Error is used and new TimeoutError("No reply in 1000 ms") sets the message. instanceof checks whether an object was made by a class (or a class that extends it):

class TimeoutError extends Error {
  name = "TimeoutError";
}
async function call(shop) {
  if (shop === "slow") throw new TimeoutError("No reply in 1000 ms");
  throw new TypeError("menu.items is not iterable");
}
async function load(shop) {
  try {
    await call(shop);
  } catch (err) {
    if (err instanceof TimeoutError) console.log("Retry later:", err.message);
    else console.log("Bug, tell the developer:", err.name, "-", err.message);
  }
}
load("slow");
load("broken");
Retry later: No reply in 1000 ms
Bug, tell the developer: TypeError - menu.items is not iterable
  • A TimeoutError is expected (the outside world was slow): retry it, or show "try again".
  • A TypeError (the built-in error for using a value the wrong way, like looping over undefined) is a bug in our code: retrying won't help, so report it.
  • In a catch, handle what you understand and rethrow the rest.

Always throw Error objects

You can throw any value, but throw "Payment gateway down" gives you a string: in the catch, err.message is undefined, typeof err is "string" and err instanceof Error is false. No name, no stack trace. Always throw new Error("...") or a subclass.

Error cause: never lose the original error

Often you catch a low-level error and throw a clearer one, like "Checkout failed for order 42". But then the real reason, "Card expired", is lost. So pass it as the cause, in the options object: new Error(message, { cause: err }).

async function readCard() {
  throw new Error("Card expired");
}
async function checkout() {
  try {
    await readCard();
  } catch (err) {
    throw new Error("Checkout failed for order 42", { cause: err });
  }
}
checkout().catch((err) => {
  console.log(err.message);
  console.log("because:", err.cause.message);
});
Checkout failed for order 42
because: Card expired

The friendly message on top, the original error kept inside it as err.cause. Wrapping like this is called error chaining. If you console.log(err) the whole error instead, Node prints both stack traces, the original under a [cause]: Error: Card expired line. When something breaks at night, that cause is what tells you why.

Trap: try/catch without await

The classic beginner mistake: a plain try/catch around an async call, with no await, outside any async function:

async function sendReceipt() {
  throw new Error("SMS service down");
}
try {
  sendReceipt();
} catch (err) {
  console.log("caught:", err.message);
}
console.log("done");
done
main.js:2
  throw new Error("SMS service down");
        ^

Error: SMS service down
    at sendReceipt (main.js:2:9)
    at Object.<anonymous> (main.js:5:3)
    ... (lines starting with "at node:internal" cut)

Node.js v24.22.2

done printed, then the crash. Calling an async function never throws on the spot. Even when its very first line throws, it just returns a rejected promise. A synchronous try/catch (one that watches only code running right now, line by line) doesn't look inside promises. Node reports the rejection once the current code has finished, which is why done came first. The same happens inside an async function: try { pay(180); console.log("Paid!"); } prints Paid! and then crashes. No await, no catch.

The last safety net: process.on("unhandledRejection")

process is Node's object for the running program, and process.on(eventName, fn) runs fn when that event happens. The "unhandledRejection" event fires for any rejection nobody handled, instead of the crash:

process.on("unhandledRejection", (err) => {
  console.log("Safety net caught:", err.message);
  process.exitCode = 1;
});
async function sendReceipt() {
  throw new Error("SMS service down");
}
sendReceipt();
console.log("App still running");
App still running
Safety net caught: SMS service down
  • process.exitCode = 1 sets the exit code Node will use when it finishes on its own, without stopping it now. echo $? prints exit code: 1, so tools still know something failed.
  • Use this to log and alert (send the error to your monitoring), not as your main error handling. The real fix is still an await or a .catch close to the call.
  • In the browser, the same idea is window.addEventListener("unhandledrejection", ...).

Common mistakes (and what really happens)

You wrote What happens Why Fix
placeOrder(); (nobody catches) Error: Payment gateway down, process exits with code 1 unhandled rejection try/catch with await, or .catch()
try { return pay(); } catch ... the catch never runs, still crashes the try ends before the promise rejects return await pay()
try { sendReceipt(); } catch ... done, then Error: SMS service down an async call never throws on the spot await it, or sendReceipt().catch(...)
await Promise.all([a, b, c]) for a page Home page failed: Biryani House is closed one rejection fails them all Promise.allSettled
await track(order) with no limit waits 3 s, or forever promises have no timeout Promise.race with an alarm
timeout without clearTimeout job done at 205 ms, program ends at 3004 ms the alarm timer is still pending .finally(() => clearTimeout(timer))
retrying every error, even payments the customer may be charged twice not every error is transient retry only timeouts/network errors (instanceof)
throw "Payment gateway down" err.message is undefined a string isn't an Error throw new Error("...")
throw new Error("Checkout failed") in a catch "Card expired" is lost the original error was dropped new Error(msg, { cause: err })
err.cause.message with no cause TypeError: Cannot read properties of undefined (reading 'message') err.cause is undefined err.cause?.message
custom error, this.name = ... before super ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor this doesn't exist until super runs call super(message) first

Mini project: a home page that never goes blank

Four restaurants. Each menu call gets a 500 ms timeout; a timeout is retried (up to 3 tries, backoff from 100 ms) but a closed shop is not; every final failure is wrapped with a cause; Promise.allSettled shows whatever loaded; and a safety net watches for anything we missed:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
class TimeoutError extends Error {
  constructor(ms) {
    super("No reply in " + ms + " ms");
    this.name = "TimeoutError";
  }
}
function timeout(promise, ms) {
  let timer;
  const alarm = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new TimeoutError(ms)), ms);
  });
  return Promise.race([promise, alarm]).finally(() => clearTimeout(timer));
}
// Fake servers: how long each shop takes on try 1, 2, 3 ("closed" = throws)
const SHOPS = { "Dosa Corner": [100], "Chai Point": [900, 150], "Biryani House": ["closed"], "Pizza Planet": [900, 900, 900] };
async function fetchMenu(shop, attempt) {
  const plan = SHOPS[shop][attempt - 1];
  if (plan === "closed") throw new Error(shop + " is closed");
  await wait(plan);
  return shop + " menu";
}
async function loadShop(shop, times = 3, delay = 100) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await timeout(fetchMenu(shop, attempt), 500);
    } catch (err) {
      const again = err instanceof TimeoutError && attempt < times;
      console.log(`  ${shop}: ${err.name} on try ${attempt}${again ? ", retrying" : ""}`);
      if (!again) throw new Error("Could not load " + shop, { cause: err });
      await wait(delay);
      delay = delay * 2;
    }
  }
}
async function home() {
  const start = Date.now();
  const names = Object.keys(SHOPS);
  const results = await Promise.allSettled(names.map((shop) => loadShop(shop)));
  results.forEach((r, i) => {
    if (r.status === "fulfilled") console.log("show:", r.value);
    else console.log("hide:", names[i], "-", r.reason.cause.message);
  });
  const ok = results.filter((r) => r.status === "fulfilled").length;
  console.log("Loaded", ok, "of", names.length, "in", Date.now() - start, "ms");
}
process.on("unhandledRejection", (err) => {
  console.log("Safety net:", err.message);
  process.exitCode = 1;
});
home();
  Biryani House: Error on try 1
  Chai Point: TimeoutError on try 1, retrying
  Pizza Planet: TimeoutError on try 1, retrying
  Pizza Planet: TimeoutError on try 2, retrying
  Pizza Planet: TimeoutError on try 3
show: Dosa Corner menu
show: Chai Point menu
hide: Biryani House - Biryani House is closed
hide: Pizza Planet - No reply in 500 ms
Loaded 2 of 4 in 1806 ms
  • Biryani House failed once: a plain Error isn't a TimeoutError, so it isn't retried. Chai Point timed out, was retried, and loaded. Pizza Planet used all 3 tries.
  • Total ≈ Pizza Planet's path: 500 + 100 (wait) + 500 + 200 (wait) + 500 = 1800 ms. All four shops load at the same time, so the page takes as long as the slowest shop, not the sum.
  • r.reason is the wrapper ("Could not load ..."); r.reason.cause is the real error. The safety net stayed silent, because every promise was handled.

Practice

  1. Make placeOrder(amount) fall back to cash when the online payment fails, and return the result.
  2. Load four menus with Promise.allSettled, two of them closed, and print the open and closed lists.
  3. Add a 500 ms timeout to two jobs: chai (300 ms) and biryani (2000 ms).
  4. Retry a ride booking that fails 3 times, allowing at most 5 tries, starting at 100 ms.
Solutions
  1. Same shape as safePay: try { const receipt = await pay(amount); return "Paid online: " + receipt; } catch (err) { console.log("Online payment failed:", err.message); return "Collect Rs " + amount + " in cash"; }, then placeOrder(180).then((result) => console.log(result));. With the failing pay, it prints Online payment failed: Payment gateway down and Collect Rs 180 in cash.

  2. const results = await Promise.allSettled([menu("Dosa Corner", 200), menu("Biryani House", 100, false), menu("Chai Point", 300), menu("Momo Hut", 150, false)]); then const open = results.filter((r) => r.status === "fulfilled").map((r) => r.value); and the same with "rejected" and r.reason.message. Printing both gives Open: [ 'Dosa Corner menu', 'Chai Point menu' ] and Closed: [ 'Biryani House is closed', 'Momo Hut is closed' ].

  3. Reuse the episode's timeout and loop over the two jobs: for (const job of [makeChai, cookBiryani]) { try { console.log(await timeout(job(), 500)); } catch (err) { console.log("Sorry:", err.message); } }, where makeChai = () => wait(300).then(() => "Chai ready"). It prints Chai ready, then Sorry: Timed out after 500 ms.

  4. Reuse the episode's retry with a job that fails while calls <= 3: retry(bookRide, 5, 100) (pass the function itself, so retry can call it again). It prints attempt 1 failed: No rider nearby (call 1), attempts 2 and 3 the same way, then Rider Ravi is coming after 706 ms: the waits were 100 + 200 + 400 = 700 ms.

Quick quiz

What does this print?

async function f() {
  throw new Error("X");
}
async function g() {
  try {
    return f();
  } catch {
    return "caught";
  }
}
g().then(
  (v) => console.log(v),
  (e) => console.log("rejected", e.message)
);
  • A. caught
  • B. rejected X
  • C. X
  • D. Nothing, it crashes
Answer

B (rejected X). Real output:

rejected X

return f() hands back f's rejected promise without awaiting it, so the try ends first and the catch never runs. g's promise rejects with X. .then(onSuccess, onFailure) takes a second function that runs on rejection; it logs rejected X, and because it handles the rejection, there's no crash. (catch { without (err) is allowed when you don't need the error.) With return await f(), it would print caught.

Interview questions

  • What is an unhandled promise rejection, and what does Node.js do with one? A rejected promise nothing ever handles. Since Node 15 it crashes the process with exit code 1.
  • Two ways to handle a rejection with async/await? try/catch around await, or .catch() on the returned promise at the call.
  • Why doesn't try { return promise; } catch {} catch the rejection? The pending promise is returned at once and the try ends; the rejection comes later. Use return await.
  • Can a synchronous try/catch catch an async function's error without await? No. An async function never throws on the spot; it returns a rejected promise.
  • Promise.all vs Promise.allSettled? all rejects at the first rejection (fail fast); allSettled waits for all and returns {status, value} / {status, reason}, never rejecting.
  • Promise.race vs Promise.any? race follows the first to settle, even a failure; any follows the first success, rejecting with AggregateError only if all fail.
  • How do you add a timeout to a promise? Promise.race it against a promise that rejects after ms, and clearTimeout in finally. For fetch, AbortSignal.timeout(ms) also cancels the request.
  • What is exponential backoff, and why? Retrying with a wait that doubles each time, up to a max number of attempts, so an overloaded service can recover. Often with jitter.
  • Which errors should you retry? Only transient ones (timeouts, busy network). Not bugs, and not non-idempotent actions (where doing it twice is not the same as once) like payments.
  • How do you tell error types apart? Custom classes extending Error, checked with instanceof (or err.name).
  • What is error.cause? The original error passed via new Error(msg, { cause: err }), so wrapping doesn't lose the real reason.
  • What is process.on("unhandledRejection") for? A last safety net to log and alert; not a replacement for proper handling.

Glossary

Term Meaning Example
Promise an object standing for a value that will be ready later wait(200)
Pending / fulfilled / rejected / settled still waiting / finished with a value / failed with an error / either of the last two { status: "rejected" }
Rejection reason the value a promise fails with (usually an Error) err in catch (err)
Unhandled rejection a rejected promise no code ever handles; crashes Node placeOrder(); with no catch
Process / crash the running program / it stopping on an error nobody handled Node.js v24.22.2 at the end
Stack trace the list of function calls that led to an error, newest first at pay (main.js:4:9)
Exit code the number a program hands the OS when it ends: 0 = OK, other = failure exit code: 1
try / catch / finally run code / handle its error / always run at the end catch (err)
.catch(fn) / .finally(fn) run fn if the promise rejects / when it settles either way placeOrder().catch(...)
.then(onOk, onFail) run onOk on success, onFail on rejection the quiz
return await wait for the promise before returning, so the try can catch safePay
Synchronous code that runs right now, line by line a plain try/catch
Rethrow throw err inside catch, passing the error on last retry attempt
Promise.all / fail fast one promise for all values / rejects at the first rejection three menus
Promise.allSettled waits for every promise, never rejects, returns report cards show: / skip:
Promise.race settles like the first promise to settle job vs alarm
Promise.any / AggregateError first success wins / the error when every promise failed first rider to answer
Combinator a function combining several promises into one all, allSettled, race, any
Timeout a time limit after which you stop waiting and treat it as a failure timeout(track(...), 1000)
Hang a call that never answers, without failing a stuck server
setTimeout / clearTimeout start a timer (returns its id) / cancel it timer = setTimeout(...)
AbortSignal.timeout(ms) a signal that cancels a fetch after ms fetch(url, { signal })
Transient error a temporary failure that may work next time Network busy
Retry / max attempts trying a job again after a failure / how many tries before giving up retry(job, 4, 200)
Exponential backoff the wait before each retry doubles 200, 400, 800 ms
Jitter a little randomness added to each retry wait 200 ms + a random 0-50 ms
Idempotent doing it twice has the same effect as once reading a menu, not paying
OTP one-time password sent by SMS for login sendOtp("Asha")
Error / err.name / err.message the built-in error object / its type name / its text new Error("Card expired")
TypeError built-in error for using a value the wrong way menu.items is not iterable
ReferenceError built-in error for a name that doesn't exist (yet) this before super
Custom error class your own error type made with extends Error TimeoutError
super(message) call the parent class constructor (Error) sets err.message
Class field a property written directly in the class body, set on every new object name = "TimeoutError";
++x / x++ add 1 and give the new value / give the old value, then add 1 if (++calls < 3)
instanceof checks whether an object was made by a class (or its subclass) err instanceof TimeoutError
Error cause / error chaining the original error kept inside a new one / wrapping errors this way { cause: err }, err.cause
process.on(event, fn) run fn when a Node process event happens "unhandledRejection", "exit"
process.exitCode the exit code Node will use when it finishes process.exitCode = 1
Safety net a last handler for errors nobody else caught: log, then fix unhandledRejection handler

Summary

  • A rejected promise nobody handles is an unhandled rejection: Node prints the error and crashes with exit code 1.
  • Put a try/catch around await, or a .catch at the call. Every promise must end at one of them.
  • An async call never throws on the spot, so no await means no catch. Inside try, always return await.
  • Promise.all fails fast; Promise.allSettled shows what you can.
  • Promises have no time limit: add a timeout with Promise.race and an alarm, and clearTimeout in finally.
  • Retry with exponential backoff and a max number of attempts, only for transient errors.
  • Tell errors apart with custom error classes and instanceof; wrap with { cause } so the original is never lost; keep process.on("unhandledRejection") as the last safety net, not the main plan.

Next episode: Functional patterns and immutability. A function quietly changes the original menu prices, and pure functions and immutability stop bugs like that.