🎓 A1Learner
🔍
0 of 50 lessons completed

Handling Async Errors

An async error is a failure inside a promise. A failed promise rejects with an error.

A function that fails

This function returns a promise that rejects with an error.

function fail() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error("Something broke")), 100);
  });
}

Catching with catch

This catches the failure from the last snippet.

fail().catch((error) => {
  console.log("Caught: " + error.message);
});

Example

function fail() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error("Something broke")), 100);
  });
}

async function main() {
  try {
    await fail();
    console.log("All good");
  } catch (error) {
    console.log("Caught: " + error.message);
  }
}

main();

Key points

  • A rejected promise carries an error.
  • The catch method runs a function when a promise rejects.
  • Try and catch work with await inside an async function.
  • Put the await line inside the try block.
  • The catch block runs when the awaited promise rejects.
  • The error message names what went wrong.

In this example, fail returns a promise that rejects with an error. The main function awaits that promise inside a try block. The awaited promise rejects, so the catch block runs. The catch block prints the error message. All good never prints.

Note

A promise that rejects with no catch crashes the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you catch an error from an awaited promise?