【发布时间】:2022-01-23 01:04:34
【问题描述】:
在重新抛出被拒绝的 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();
test() 中的所有三个函数调用都会打印以下内容:
Error: a
at <anonymous>:4:31
我本来希望是这样的:
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)
调用函数不应该是堆栈跟踪的一部分吗?
我在 Google Chrome 中测试了这段代码。
【问题讨论】:
-
基本上是因为它是由
setTimeout而不是a调用的 -
看看你是否为所有这些函数命名会有所帮助。
标签: javascript error-handling promise stack-trace