CodeBlanks Logo Icon CodeBlanks

Async error handling

JavaScript course · Intermediate · Lesson 80/134

Learn to catch errors in async functions with try/catch.

Catching async errors with try/catch

In a promise chain you use catch; with async/await you use a try...catch block. When an async function awaits a promise that is rejected, the error falls into the catch block.

async function loadPost() {
  try {
    const post = await fetchPost();
  } catch (err) {
    console.error(err);
  }
}

This structure mirrors error handling in synchronous code, which is why async/await is considered more readable.

Re-throwing an error

Sometimes you want to catch an error and then pass it on. To do that, you re-throw it with throw inside the catch block. The calling code then catches it with its own try/catch.

async function loadItem() {
  try {
    return await fetchItem();
  } catch (err) {
    console.error('Loading failed');
    throw err;
  }
}

This pattern lets you log the error while still forwarding it to the caller.

Exercise Add error handling

Write async function loadOrder(). Inside a try block, call await fetchOrder() and assign the result to an order variable. Add a catch (err) block that logs the error with console.error(err).

Show example solution
async function loadOrder() {
  try {
    const order = await fetchOrder();
  } catch (err) {
    console.error(err);
  }
}

Test yourself

  1. What does the following code do?

    async function f() {
      try {
        const x = await Promise.reject(new Error('boom'));
      } catch (err) {
        console.log(err.message);
      }
    }
    • Prints 'boom'
    • Throws an uncaught error
    • Prints undefined
    • Does nothing
    Show answer

    Prints 'boom' — Correct! The rejected promise's error falls into catch and its message is logged.

  2. Add the catch block

    async function loadItem() {
      try {
        const item = await fetchItem();
      } ____ {
        console.error(err);
      }
    }
    Show answer
    async function loadItem() {
      try {
        const item = await fetchItem();
      } catch {
        console.error(err);
      }
    }
  3. Match error-handling concepts

    await Promise.reject(err)
    falls into the catch block
    try { await ... }
    continues inside try on success
    throw err
    forwards the error to the caller
    catch (err)
    receives the error as err

All lessons in Intermediate