How do I catch thrown errors with async / await?

2019-06-26 00:41发布

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))

2条回答
Fickle 薄情
2楼-- · 2019-06-26 01:24

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-06-26 01:24

async is meant to be used with Promises. If you reject the promise, then you can catch the error, if you resolve the promise, that becomes the return value of the function.

async function helloWorld () {
  return new Promise(function(resolve, reject){
    reject('error')
  });
}


try {
    await helloWorld();
} catch (e) {
    console.log('Error occurred', e);
}
查看更多
登录 后发表回答