JavaScript重新抛出异常时如何保留堆栈跟踪信息

5
在Chrome中,当发生异常时,它会在控制台日志中打印堆栈跟踪信息。这非常有用,但不幸的是,在重新抛出异常的情况下,会导致问题。
} catch (e) {
    if (foo(e)) {
        // handle the exception
    } else {
        // The stack traces points here
        throw e;
    }
}

很不幸,如果异常来自事件处理程序,以下代码在 jQuery.js 中会导致所有异常出现此问题。

try {
    while( callbacks[ 0 ] ) {
        callbacks.shift().apply( context, args );
    }
}
// We have to add a catch block for
// IE prior to 8 or else the finally
// block will never get executed
catch (e) {
    throw e;
}
finally {
    fired = [ context, args ];
    firing = 0;
}

有没有一种方法可以改变 throw e;,使得异常可以使用原来的堆栈信息再次抛出?

3
可能是如何在JavaScript中重新抛出异常但保留堆栈?的重复问题。 - cmroanirgo
2个回答

2
这是Chrome浏览器中已知的问题,不幸的是,我目前不知道有什么解决方法。

1
你唯一能做的就是获取原始堆栈并将其打印出来。 我在单元测试工具中使用它。
try{
  ...
}
catch(e){
    console.log(e.stack);
    console.log(e.message);
    throw(e);
}

1
根据这个帖子(https://bugs.chromium.org/p/chromium/issues/detail?id=60240)的说法,现在在Chrome中重新抛出异常是可以工作的,但我发现它只能在单个文件中定义的代码中有效。我的重新抛出异常位于另一个文件中,所以它无法工作。 - Philip Taylor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接