How to handle an error in async await in JavaScript


Last updated on Sep 24, 2020 by Suraj Sharma

In this tutorial, you will learn how you can handle an error or a promise rejection in JavaScript async/await.

Consider, we have a Promise

const getAsyncOddNumber = (number) => {
  return new Promise((resolve, reject) => {
      if(number<=0) {
        reject('Number must be greater than zero');
      } else {
        if (number % 2 !== 0)
          resolve(`${number} is an odd number`);
          resolve(`${number} is not an odd number`);
    }, 500);

If the number is less than and equals to zero, then the promise would get rejected, resulting in a JavaScript error.

const mainFn = async () => {
  const message = await getAsyncOddNumber(-2);
  console.log(message); // nothing gets printed


To successfully handle the error in async/await, we are going to use JavaScript try...catch statement.

const mainFn = async () => {
  try {
    const message = await getAsyncOddNumber(-2);
  } catch(error) {
    console.log(error); // 'Number must be greater than zero'


Related Solutions

Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.