【问题标题】:nodejs - catch error at any deeper levelnodejs - 在任何更深层次上捕获错误
【发布时间】:2018-03-16 22:39:48
【问题描述】:

如何捕获async 函数中引发的错误。如下例所示:

I) 工作示例(可捕获错误)

(async () => {
  try {
    // do some await functions

    throw new Error("error1")
  }
  catch(e) {
    console.log(e)
  }
})()

控制台

Error: error1
    at __dirname (/home/test.js:25:11)
    at Object.<anonymous> (/home/quan/nodejs/IoT/test.js:30:3)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Function.Module.runMain (module.js:665:10)
    at startup (bootstrap_node.js:201:16)
    at bootstrap_node.js:626:3

II) 但是如果我将try-catch 放在async 之外,异常就会变得无法捕获,如下所示:

try {
  (async () => {
    throw new Error("error1")
  })()
}
catch(e) {
  console.log(e)
}

控制台:

(node:3494) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: error1

(node:3494) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

有没有办法捕捉从async 抛出的错误,如 II 所示?

我必须要求这个来简化我的代码,其中包含许多switch-case,我不想在每个switch-case 中处理try-catch

问候,

【问题讨论】:

    标签: node.js async-await try-catch


    【解决方案1】:

    您可以使用 Promise 来解决这个问题,在 Promise 链的末尾添加 catch 将有助于捕获异步错误。

    function resolveAfter2Seconds(x) {
            return new Promise(resolve => {
                if(x === 'Error'){
                    throw Error('My error')
                }
    
                setTimeout(() => {
                resolve(x);
    
              }, 2000);
            }).catch(function (e){
                console.log('error-------------------', e)
            });
          }
    
          async function add1(x) {
            const a = await resolveAfter2Seconds('success');
            const b = await resolveAfter2Seconds('Error');
            return x + a + b;
          }
    
          add1();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2021-02-25
      • 2022-07-11
      相关资源
      最近更新 更多