【问题标题】:Why does the stack trace of an Error that is returned by a Promise seem to be incomplete?为什么 Promise 返回的 Error 的堆栈跟踪似乎不完整?
【发布时间】: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


【解决方案1】:

异步堆栈跟踪(您在生产中获得的那些)仅适用于异步函数,因此当您有一个不是异步的函数并且仅使用承诺时,链不会缝合。您可以在the design document 中阅读更多关于实现的信息,幸运的是,修复非常简单:

// 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');
}

很高兴记录:

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)

【讨论】:

    【解决方案2】:

    我可能是错的,但我相信这是因为您在 setTimeout 中创建了一个匿名函数,然后会因错误而被抛出。

    也许不是最干净的,但对于我放入 logPrefix 的每个错误,并执行以下操作。只是意味着您可以轻松调试错误。

    const logPrefix = '[my-function-name]'
    throw new Error(`${logPrefix} - The error maybe with ${error} injected`)
    

    如果我的函数在一个类中或者我可能会执行以下操作

    const logPrefix = '[className.methodName]'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多