问题描述
我有两 (2) 个代码做同样的事情,但其中一个 (Code01) 在 vscode 中使用调试器运行时显示未捕获的异常,而另一个则没有 (Code02)。
有人可以帮我理解其中的区别吗?
// ./vscodeDebuggerAsyncCatchExceptionTest01.js
// "Code01" - This code has an uncaught exception.
"use strict";
async function thisThrows() {
throw new Error("Thrown from thisThrows()"); // uncaught exception here
}
async function myFunctionThatCatches() {
return await thisThrows().catch((e) => {
throw e;
});
}
async function run() {
await myFunctionThatCatches().catch((e) => {
throw e;
});
}
run()
.catch( e => {
console.error(e);
console.error("++++ ERROR was caught");
})
// ./vscodeDebuggerAsyncCatchExceptionTest02.js
// "Code02" - This code runs well. All exception are handled.
"use strict";
async function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
async function myFunctionThatCatches() {
return await thisThrows().catch((e) => {
throw e;
});
}
async function run() {
try {
await myFunctionThatCatches().catch((e) => {
throw e;
});
} catch (e) {
throw e;
}
}
run()
.catch( e => {
console.error(e);
console.error("++++ ERROR was caught");
})
这是“Code02”vscode 调试器输出:
发生异常:错误:从 thisThrows() 处抛出 这抛出 (d:\JavaProjects\JavaScript\LWPS01\libJS\LoProbe\vscodeDebuggerAsyncCatchExceptionTest01.js:7:9) 在 myFunctionThatCatches (d:\JavaProjects\JavaScript\LWPS01\libJS\LoProbe\vscodeDebuggerAsyncCatchExceptionTest01.js:11:16) 运行时 (d:\JavaProjects\JavaScript\LWPS01\libJS\LoProbe\vscodeDebuggerAsyncCatchExceptionTest01.js:18:9) 在对象。 (d:\JavaProjects\JavaScript\LWPS01\libJS\LoProbe\vscodeDebuggerAsyncCatchExceptionTest01.js:23:1) 在 Module._compile (internal/modules/cjs/loader.js:1063:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) 在 Module.load (internal/modules/cjs/loader.js:928:32) 在 Function.Module._load (internal/modules/cjs/loader.js:769:14) 在 Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) 在内部/main/run_main_module.js:17:47
解决方法
哇,我在“Code01”中发现了问题。
“Code01”中的问题是未捕获的异常链从“thisThrows()”上的异常到调用“run()”函数中断。
由于所有函数都是“异步”(async),代码必须等待,直到在“thisThrows()”函数中“抛出错误”执行完毕,通过添加“await”关键字。
以下是“Code04”,问题已解决。
以/*A*/开头的行表示解决“Code01”中问题的更正代码行。
"use strict";
async function thisThrows() {
/*A*/ throw await new Error("Thrown from thisThrows()");
// "await" keyword was included in above line of code.
}
async function myFunctionThatCatches() {
return await thisThrows().catch((e) => {
throw e;
});
}
async function run() {
await myFunctionThatCatches().catch((e) => {
throw e;
});
}
run()
/*A*/ .then( r => console.log( "!!!! Exution was completed successfully") )
.catch( e => {
console.error(e);
console.error("++++ ERROR was caught");
})