Javascript Fundamentals ยท Promises & Async

Handle async errors with try/catch

try/catch around await

Handle async errors with try/catch

A request fails and you want to show a fallback, but the failure happens far from the line that started it. For synchronous code you already reach for try / catch; the question is whether that still catches a result that arrives later.

A rejected promise becomes a thrown error at the await. So the natural way to handle async failure is the same try / catch you already use for synchronous code:

async function load(id) {
  try {
    const user = await getUser(id);
    return user;
  } catch (error) {
    return null; // getUser rejected
  }
}

When the awaited promise rejects, execution jumps straight from the await to the catch block, skipping the rest of the try. A finally block runs afterwards either way, which is the place to release resources:

try {
  const data = await fetchData();
  return data;
} catch (error) {
  return fallback;
} finally {
  clearLoader();
}

This is the same failure you would otherwise route through .catch, written inline instead. If you do not catch it, the error propagates: an async function that throws returns a rejected promise, and the rejection travels to whoever awaits it โ€” or, if nobody does, it becomes an unhandled rejection.

You are about to answer a short quiz on try / catch around await.

  1. When an awaited promise rejects, execution jumps to the surrounding catch block.
  2. Wrap an await in a try / ___ block to handle a rejection.
  3. An async function that throws returns a rejected promise.
  4. The ___ block runs whether the try succeeded or threw.
  5. If an async function rejects and nobody catches it, it becomes an unhandled rejection.
  6. An await inside a try block behaves like a synchronous ___ when the promise rejects.
  7. A rejection from an awaited promise can be handled with a catch method on the promise instead of a try / catch block.