AFo*_*eee 4 javascript error-handling stack-trace promise
在重新抛出被拒绝的 Promise 的错误时,我注意到堆栈跟踪似乎不完整。
例如:
// returns a Promise that is later on rejected.
function a() {
return new Promise((resolve, reject)=>{
setTimeout(()=>reject(new Error("a")), 2000);
});
}
async function b() {
await a();
}
async function c() {
await b();
}
// testing
async function test() {
let printError = (error)=>console.log(error.stack);
await a().catch(printError);
await b().catch(printError);
await c().catch(printError);
}
test();
Run Code Online (Sandbox Code Playgroud)
所有三个函数调用都会test()打印以下内容:
Error: a
at <anonymous>:4:31
Run Code Online (Sandbox Code Playgroud)
我本来期望的是这样的:
Error: a
at <anonymous>:4:31
at new Promise (<anonymous>)
at a (<anonymous>:3:12)
at b2 (<anonymous>:13:15)
at c2 (<anonymous>:21:15)
at test (<anonymous>:32:2)
Run Code Online (Sandbox Code Playgroud)
调用函数不应该是堆栈跟踪的一部分吗?
我在 Google Chrome 中测试了这段代码。
异步堆栈跟踪(您在生产中获得的堆栈跟踪)仅适用于异步函数,因此当您有一个非异步函数并且仅使用 Promise 时,链将不会缝合。您可以在设计文档中阅读有关实现的更多信息,幸运的是修复非常简单:
// the function has to be async
async function a() {
// isolate areas that have to use raw promises
await new Promise((resolve, reject)=>{
setTimeout(()=>resolve(), 2000);
});
// throw the error from inside the function
throw new Error('a');
}
Run Code Online (Sandbox Code Playgroud)
哪个高兴地记录:
Error: a
at a (<anonymous>:6:11)
at async b (<anonymous>:10:5)
at async c (<anonymous>:14:5)
at async test (<anonymous>:23:5)
Run Code Online (Sandbox Code Playgroud)