开发者

JavaScript rethrowing an Exception preserving the stack trace

开发者 https://www.devze.com 2023-02-16 07:19 出处:网络
In Chrome, when an exception occurs, it prints a stack trace to the console log. This is extremely useful, but unfortunately in cases where an exception has been rethrown this causes an issue.

In Chrome, when an exception occurs, it prints a stack trace to the console log. This is extremely useful, but unfortunately in cases where an exception has been rethrown this causes an issue.

} catch (e) {
    if (foo(e)) {
        // handle the exception
    } else {
        // The stack traces points here
        throw e;
    }
}

Unfortunately, the following code in jQuery.js is causing all exceptions to have this issue if they're from inside event handlers.

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

Is there a way to change the throw e; so that the exception is rethrown with the same stack trace?


This is a known bug in Chrome, and unfortunately there's no workaround that I'm aware of.


The best you can do is grab the original stack and print it. I use this in unit testing tools.

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

精彩评论

暂无评论...
验证码 换一张
取 消