Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch thrown errors with async / await?

Here's some code:

  import 'babel-polyfill'

  async function helloWorld () {
    throw new Error ('hi')
  }

  helloWorld()

I also went deep and tried this as well:

  import 'babel-polyfill'

  async function helloWorld () {
    throw new Error ('hi')
  }

  async function main () {
    try {
      await helloWorld()
    } catch (e) {
      throw e
    }
  }

  main()

and:

import 'babel-polyfill'

 async function helloWorld () {
   throw new Error ('hi')
 }

try {
 helloWorld()
} catch (e) {
 throw e
}

This works:

import 'babel-polyfill'

async function helloWorld () {
  throw new Error('xxx')
}

helloWorld()
.catch(console.log.bind(console))
like image 865
ThomasReggi Avatar asked Nov 06 '15 08:11

ThomasReggi


People also ask

What happens when an error is thrown inside an async function?

What happens when an error is thrown inside an async function? Error thrown from async function is a rejected promise catch() chain function to catch the error within the promise chain.

What block of code do we use to catch errors with async await?

catch(err => { console. error(err) }); But there is another way: the mighty try/catch block! If you want to handle the error directly inside the async function, you can use try/catch just like you would inside synchronous code.

Which is the best standard approach on error handling for async function?

Error handlingA try/catch block can be used to handle asynchronous errors in an async function. Alluding to the fact that an async function always return a Promise, one can opt to use a . catch() in place of a whole try/catch block.


1 Answers

So it's kind of tricky, but the reason you're not catching the error is because, at the top level, the entire script can be thought of as a synchronous function. Anything you want to catch asynchronously needs to be wrapped in an async function or using Promises.

So for instance, this will swallow errors:

async function doIt() {
  throw new Error('fail');
}

doIt();

Because it's the same as this:

function doIt() {
  return Promise.resolve().then(function () {
    throw new Error('fail');
  });
}

doIt();

At the top level, you should always add a normal Promise-style catch() to make sure that your errors get handled:

async function doIt() {
  throw new Error('fail');
}

doIt().catch(console.error.bind(console));

In Node, there is also the global unhandledRejection event on process that you can use to catch all Promise errors.

like image 156
nlawson Avatar answered Sep 18 '22 00:09

nlawson