我可以在不使用await的情况下从异步中捕获错误吗? [英] Can I catch an error from async without using await?

查看:266
本文介绍了我可以在不使用await的情况下从异步中捕获错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以捕获来自未等待的异步调用的错误,发送到原始封装的try / catch,还是引发未捕获的异常?



这是一个示例我的意思是:

  async function fn1(){
console.log('execution fn1');
}

异步函数fn2(){
console.log('执行fn2');
抛出新错误('来自fn2');
}

async function test(){
try {
await fn1();
fn2();
}
catch(e){
console.log('测试中出现错误:',e);
}
}

test();

在这种情况下,从 fn2 将被静默吞噬,绝对不会被原来的尝试/捕获捕获。我相信这是预期的行为,因为 fn2 很可能被推到事件循环中,以便在将来某个时候完成,并且 test 完成时无关紧(这是故意的)。



有没有办法确保错误不会被像这样的结构意外吞没这个,没有把 try / catch 内部放到 fn2 并做一些像发出错误的事情?我甚至会在不知道如何抓住它的情况下解决一个未被捕获的错误,我认为 - 我不希望抛出的错误是我正在编写的典型程序流程,但是吞下错误会使调试相对烦人。



旁注,我正在使用Babel来使用babel-runtime变换来转换代码,并使用节点执行它。

解决方案

处理未处理的被拒绝的本机承诺(以及async / await使用本机承诺)是V8中现在支持的功能。当被拒绝的承诺未处理时,它在最新的Chrome中用于输出调试信息;请在:

  process.on('unhandledRejection',function(reason,p){
console.log( 未处理的拒绝:承诺,p,原因:,原因);
//特定于应用程序的日志记录,抛出一个n错误或其他逻辑
});


Can errors from a non-awaited async call be caught, sent to an original encapsulating try/catch, or raise an uncaught exception?

Here's an example of what I mean:

async function fn1() {
    console.log('executing fn1');
}

async function fn2() {
    console.log('executing fn2');
    throw new Error('from fn2');
}

async function test() {
    try {
        await fn1();
        fn2();
    }
    catch(e) {
        console.log('caught error inside test:', e);
    }
}

test();

In this scenario, the error thrown from fn2 will be swallowed silently, and definitely not caught by the original try/catch. I believe this is expected behavior, since fn2 is most likely being shoved off to the event loop to finish at some point in the future, and test doesn't care when it finishes (which is intentional).

Is there any way to ensure that errors are not accidentally swallowed by a structure like this, short of putting a try/catch internal to fn2 and doing something like emitting an error? I would even settle for an uncaught error without knowing how to catch it, I think -- I don't expect thrown errors to be typical program flow with what I am writing, but swallowing errors makes it relatively annoying to debug.

Side note, I'm using Babel to transpile the code using the babel-runtime transform, and executing it with node.

解决方案

Dealing with unhandled rejected native promises (and async/await uses native promises) is a feature supported now in V8. It's used in the latest Chrome to output debugging information when a rejected promise is unhandled; try the following at the Babel REPL:

async function executor() {
  console.log("execute");
}

async function doStuff() {
  console.log("do stuff");
  throw new Error("omg");
}

function handleException() {
  console.error("Exception handled");
}

(async function() {
  try {
      await executor();
      doStuff();
  } catch(e) {
      handleException();
  }
})()

You see that, even though the exception from doStuff() is lost (because we're not using await when we call it), Chrome logs that a rejected promise was unhandled to the console:

This is also available in Node.js 4.0+, though it requires listening to a special unhandledRejection event:

process.on('unhandledRejection', function(reason, p) {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
});

这篇关于我可以在不使用await的情况下从异步中捕获错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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