简体   繁体   English

async方法何时抛出,你如何捕获它们?

[英]When do async methods throw and how do you catch them?

From node doc : 从节点doc

A handful of typically asynchronous methods in the Node.js API may still use the throw mechanism to raise exceptions that must be handled using try / catch. Node.js API中的一些典型异步方法仍然可以使用throw机制来引发必须使用try / catch处理的异常。 There is no comprehensive list of such methods; 没有这些方法的全面清单; please refer to the documentation of each method to determine the appropriate error handling mechanism required. 请参阅每种方法的文档,以确定所需的相应错误处理机制。

Can someone bring example of such function which is async and still throws? 有人能带来这种异步但仍然抛出的功能的例子吗? How and when do you catch the exception then? 你如何以及何时捕获例外呢?

More particularly. 更具体地说。 Do they refer to such function: 他们是否提到这样的功能:

try
{

   obj.someAsync("param", function(data){
                    console.log(data);
                 });
}catch(e)
{

}

Now normally I know above doesn't make sense -because when the callback executes, try block could have been already exited. 现在通常我知道上面没有意义 - 因为当回调执行时, try块可能已经退出。

  • But what kind of example does the excerpt from documentation refer to? 但文献摘录中提到的是什么样的例子呢? If async method throws as they say it, where, when and how should I handle it? 如果异步方法按照它们的说法抛出我应该在何处,何时以及如何处理它? (or maybe if you show such function can you show where in its doc it says how to handle it as mentioned on the quote?) (或者,如果你展示了这样的功能,你可以在它的文档中显示它如何处理它,如报价中提到的那样吗?)

The async methods like the one from your example usually throw for programmer errors like bad parameters and they call the callback with error for operational errors. 像你的例子中那样的异步方法通常会抛出程序员错误,比如错误的参数,并且它们会因操作错误而调用带有错误的回调。

But there are also async functions in ES2017 (declared with async function ) and those signal errors by rejecting the promise that they return - which turn into a thrown exception when you use them with await keyword. 但是ES2017中也存在异步函数(使用async function声明),并且通过拒绝它们返回的声明来发出错误信号 - 当您将它们与await关键字一起使用时,它们会变成抛出的异常。

Examples: 例子:

function x(arg, cb) {
    if (!arg) throw new Error('Programmer error: bad arguments');
    setTimeout(() => {
        cb(new Error('Operational error: something bad happened'));
    }, 2000);
}

Now when you use it you usually don't want to handle programmer errors - you want to fix them. 现在,当你使用它,你通常希望处理程序员的错误-你想解决这些问题。 So you don't do this: 所以你不这样做:

try {
    x();
} catch (err) {
    // Why should I handle the case of bad invocation
    // instead of fixing it?
}

And the operational errors you handle like this: 你处理的操作错误如下:

x(function (err) {
    if (err) {
        // handle error
    } else {
        // success
    }
});

Now, if you have a function that doesn't take a callback but returns a promise: 现在,如果你有一个不接受回调但返回一个承诺的函数:

function y() {
    return new Promise((res, rej) => setTimeout(() => rej('error'), 2000));
}

Then you handle the error like this: 然后你处理这样的错误:

y().catch(error => {
    // handle error
});

or, while using await : 或者,在使用await

try {
    await y();
} catch (err) {
    // handle error
}

For more info on the difference between operational errors and programmer errors see: 有关操作错误和程序员错误之间差异的更多信息,请参阅:

For more info on the promises and async / await see the links in this answer . 有关promises和async / await更多信息,请参阅此答案中的链接。

afaik there are three ways a async function could "throw"; afaik异步函数可以通过三种方式“抛出”; and how to catch each of these: 以及如何捕捉这些:

  • as any other function (aka. someone messed up): I'd not catch these cases because they should not be in my code, and catching such errors makes it harder to find and fix em. 任何其他功能(也就是某人搞砸了):我不会抓住这些情况,因为它们不应该在我的代码中,并且捕获这些错误会使查找和修复它们变得更加困难。

 function foo(){ //someone messed up, better fixing than catching this return new Prooooooooooomise((resolve) => 42); } try { foo(); }catch(err){ console.error(err); } 

  • Promises: 公司承诺:

 function foo(){ return Promise.resolve('bar') } foo().then(value => value =========> 'error') .catch(err => { console.error(err); return "fixedValue"; }); 

  • And Nodes callback syntax/pattern: 和节点回调语法/模式:

 function foo(value, callback){ setTimeout(function(){ if(Math.random() < .5){ callback("I don't like to", undefined); }else{ callback(null, value * 2); } }, 500); } foo(21, function(err, data){ if(err){ //no try..catch at all console.error(err); }else{ //do whatever with data } }) 

These are the most common async errors you'll come along; 这些是你最常见的异步错误; well, the first one is just a plain bug in an async mothod. 好吧,第一个只是异步方法中的一个普通错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM