如何通过异步/等待来捕获丢失的错误? [英] How do I catch thrown errors with async / await?

查看:144
本文介绍了如何通过异步/等待来捕获丢失的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些代码:

  import'babel-polyfill'

async函数helloWorld() {
throw new Error('hi')
}

helloWorld()

我也很深,也试过了:

  import'babel-polyfill'

异步函数helloWorld(){
throw new Error('hi')
}

异步函数main(){
try {
await helloWorld()
} catch(e){
throw e
}
}

main()

和:

  import 'babel-polyfill'

异步函数helloWorld(){
throw new Error('hi')
}

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

这样做:

  import'babel-polyfill'

async function helloWorld(){
抛出新的错误或('xxx')
}

helloWorld()
.catch(console.log.bind(console))
/ pre>

解决方案

所以这很棘手,但是你没有抓住错误的原因是因为在顶层,整个脚本可以被认为是一个同步的功能。任何你想要异步捕获的东西需要被包裹在一个 async 函数或使用Promises。



所以例如,这将吞下错误:

 异步函数doIt(){
throw new Error ('失败');
}

doIt();

由于与此相同:

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

doIt();

在顶层,你应该总是添加一个普通的Promise样式的catch()来确保您的错误得到处理:

 异步功能doIt(){
throw new Error ('失败');
}

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

在Node中,还有全局 unhandledRejection 事件,过程,可用于捕获所有Promise错误。


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

解决方案

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.

这篇关于如何通过异步/等待来捕获丢失的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆