如何处理Node.js中的异步错误 [英] How to handle asynchronous error in Node.js

查看:126
本文介绍了如何处理Node.js中的异步错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bluebird的Promise.try功能是否可以替代.由于我正在使用async/await对添加蓝鸟依赖项不感兴趣.

Is there any alternative to Bluebird's Promise.try function. As I'm using async/await not interested in adding bluebird dependency.

是否有更好的方法来捕获Node.JS

Is there a better way to capture asynchronous error in Node.JS

await Promise.try(async function() {
    // Some code with async operations like readline
    await this.nextCall(batchData, true);
}).catch(async function(err) {
    // My error handling
});

Node.js 10.x中有任何内置函数吗?

Any inbuilt functions in Node.js 10.x ?

更新:

是否有更好的方法来捕获Node.JS

Is there a better way to capture asynchronous error in Node.JS

try {
    let interfaceVal = lineReader.createInterface({
        input: fs.createReadStream(filePath)
    });
    interfaceVal.on('line', async (line) => {
        throw new Error('My custom Error');
    });
    // some sync operations
} catch(e) {
    // This catch wont get called with custom error
    console.log(e);
}

是否有捕获此类异步错误的主意?

Any idea to capture such asynchronous errors ?

推荐答案

没有理由用Promise.try包装async函数. Promise.try的目的是类似地处理同步错误和拒绝:

There is no reason to wrap async function with Promise.try. The purpose of Promise.try is to handle both synchronous errors and rejections similarly:

从Promise.try开始承诺链.任何同步异常都将变成对已返回的Promise的拒绝.

Start the chain of promises with Promise.try. Any synchronous exceptions will be turned into rejections on the returned promise.

这已经用async完成了,因为它总是返回承诺.

This is already done with async since it always returns a promise.

这可以在async IIFE的顶层使用:

This can be used at top level with async IIFE:

(async function() {
    await this.nextCall(batchData, true);
})().catch(console.error);

或者如果嵌套了async,则可以省略,可以使用try..catch在父async函数中处理拒绝,如另一个答案所解释.

Or in case async is nested it can be omitted, a rejection can be handled in parent async function with try..catch, as another answer explains.

在这种情况下,只能在async函数内部捕获错误:

In this case an error can be caught only inside async function:

    interfaceVal.on('line', async (line) => {
      try {
        throw new Error('My custom Error');
      } catch (err) {
        console.error(err);
      }
    });

使用非承诺API(节点流)不允许对带有promise的错误进行处理.流回调将忽略被拒绝的承诺,并且不允许将错误传播到流之外.

The use of non-promise API (Node stream) doesn't allow for error handling with promises. Stream callback ignores rejected promises and doesn't allow to propagate the error outside the stream.

仅当预期将回调称为once时,才可以将其转换为promise. line并非如此.在这种情况下,可以使用异步迭代器,这是其用例之一.

Callbacks can be converted to promises only when they are expected to be called once. This is not the case with line. In this case asynchronous iterator can be used, this one of its use cases.

可以使用 p-event 将事件发射器转换为异步迭代器,并使用async函数内部:

try {
    let interfaceVal = lineReader.createInterface({
        input: fs.createReadStream(filePath)
    });

    const asyncIterator = pEvent.iterator(interfaceVal, 'line', {
      resolutionEvents: ['close']
    });

    for await (const event of asyncIterator) {
        console.log('line', event);
        // throw new Error('My custom Error');
    }
} catch(e) {
    console.log(e);
}

这篇关于如何处理Node.js中的异步错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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