JavaScript rethrowing an Exception preserving the stack trace
Asked Answered
A

2

5

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?

Approximate answered 9/3, 2011 at 17:47 Comment(1)
Possible duplicate of How can I rethrow an exception in Javascript, but preserve the stack?Corron
P
3

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

Panga answered 9/3, 2011 at 17:52 Comment(0)
H
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);
}
Hoatzin answered 12/4, 2016 at 13:50 Comment(1)
Note: According to this thread(bugs.chromium.org/p/chromium/issues/detail?id=60240) rethrowing works in Chrome now, but I find it only works in code defined in a single file. My rethrow is in a different file, and its not working.Hoatzin

© 2022 - 2024 — McMap. All rights reserved.