JavaScript重新抛出异常,保留堆栈跟踪

时间:2011-03-09 17:47:12

标签: javascript stack-trace throw

在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 个答案:

答案 0 :(得分:2)

这是一个known bug in Chrome,很遗憾没有我知道的解决方法。

答案 1 :(得分:0)

您可以做的最好的事情是抓住原始堆栈并进行打印。 我在单元测试工具中使用它。

try{
  ...
}
catch(e){
    console.log(e.stack);
    console.log(e.message);
    throw(e);
}

答案 2 :(得分:-1)

在我的情况下,console.log()是不可能的。我所做的是:

}catch( error ){
 // 'throw' replaces the stack trace.
 // To preserve the stack add it to the message.
 error.message += '; Stack trace: ' + error.stack;
 throw error;
}
相关问题