问题
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 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?
回答1:
This is a known bug in Chrome, and unfortunately there's no workaround that I'm aware of.
回答2:
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);
}
回答3:
In my situation console.log() was not possible. What I did is:
}catch( error ){
// 'throw' replaces the stack trace.
// To preserve the stack add it to the message.
error.message += '; Stack trace: ' + error.stack;
throw error;
}
来源:https://stackoverflow.com/questions/5249960/javascript-rethrowing-an-exception-preserving-the-stack-trace