如何使用async/await捕获抛出的错误

How do I catch thrown errors with async / await?

本文关键字:错误 何使用 async await      更新时间:2023-09-26

下面是一些代码:

  import 'babel-polyfill'
  async function helloWorld () {
    throw new Error ('hi')
  }
  helloWorld()

我也深入尝试了这个:

  import 'babel-polyfill'
  async function helloWorld () {
    throw new Error ('hi')
  }
  async function main () {
    try {
      await helloWorld()
    } catch (e) {
      throw e
    }
  }
  main()

和:

import 'babel-polyfill'
 async function helloWorld () {
   throw new Error ('hi')
 }
try {
 helloWorld()
} catch (e) {
 throw e
}

这项工作:

import 'babel-polyfill'
async function helloWorld () {
  throw new Error('xxx')
}
helloWorld()
.catch(console.log.bind(console))

async用于Promises。如果您拒绝promise,那么您可以catch错误,如果您解决了promise,则该错误将成为函数的返回值。

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

try {
    await helloWorld();
} catch (e) {
    console.log('Error occurred', e);
}

所以这有点棘手,但您没有捕捉到错误的原因是,在顶层,整个脚本可以被视为同步函数。任何想要异步捕获的内容都需要封装在async函数中或使用Promises。

例如,这将吞噬错误:

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

因为它和这个一样:

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

在顶层,您应该始终添加一个普通的Promise风格的catch(),以确保您的错误得到处理:

async function doIt() {
  throw new Error('fail');
}
doIt().catch(console.error.bind(console));

在Node中,进程上还有全局unhandledRejection事件,您可以使用它来捕获所有Promise错误。

要从异步函数中捕获错误,可以等待错误:

async function helloWorld () {
  //THROW AN ERROR FROM AN ASYNC FUNCTION
  throw new Error('hi')
}
async function main() {
  try {
    await helloWorld()
  } catch(e) {
    //AWAIT THE ERROR WITHIN AN ASYNC FUNCTION
    const error = await e
    console.log(error)
  }
}
main()

或者,您可以等待错误消息:

async function main() {
  try {
    await helloWorld()
  } catch(e) {
    //AWAIT JUST THE ERROR MESSAGE
    const message = await e.message
    console.log(message)
  }
}
相关文章: