node.js - 如何处理 Node.js 中的异步错误

标签 node.js error-handling promise async-await bluebird

Bluebird 的 Promise.try 函数有其他替代方案吗?因为我正在使用 async/await 对添加 bluebird 依赖项不感兴趣。

有没有更好的方法来捕获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 中有内置函数吗?

更新:

有没有更好的方法来捕获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 won't get called with custom error
    console.log(e);
}

有办法捕获此类异步错误吗?

最佳答案

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

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

这已经通过 async 完成,因为它总是返回一个 promise 。

这可以在顶层与async IIFE一起使用:

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

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

<小时/>

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

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

使用非 promise API( Node 流)不允许使用 promise 进行错误处理。流回调忽略被拒绝的 promise ,并且不允许将错误传播到流之外。

只有当回调预计被调用一次时,才能将其转换为promise。 line 的情况并非如此。在这种情况下可以使用异步迭代器,this one of its use cases .

事件发射器可以通过 p-event 转换为异步迭代器并在 async 函数中使用 for wait of 进行迭代:

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 - 如何处理 Node.js 中的异步错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52837091/

相关文章:

node.js - mongodb 聚合,将数组插入到文档的现有数组中

node.js - 在将 Passport 与 koa 一起使用时尝试生成 jsonwebtoken 时 ctx.passport 未定义?

node.js - z shell 问题,运行别名并得到这个 "zsh: parse error near ` }' "

php - 捕获 token_get_all (Tokenizer) 抛出的错误

node.js - 根据条件逻辑调用Q Promise

javascript - 使用 promise /构造 promise 链时,如何设计/集成错误处理?

javascript - 如何使用 Promise 返回函数调用

javascript - 如何用async/await获取第二个 `then`回调参数?

java - 我可以通过在Java的属性文件中列出多个异常来捕获多个异常吗?

r - read.table()不容许丢失数据吗?