0
如何捕獲在async
函數內拋出的錯誤。正如我下面的例子:nodejs - 在任何更深層次捕獲錯誤
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),但如果我把async
try-catch
外,異常變得抓不到,像如下:
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
。
問候,