Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any workaround to rethrow an exception and preserve the stacktrace in Javascript?

I know that Chrome has a known bug not preserving the stacktrace when rethrowing an exception in Javascript.

I have the following code running in Chrome:

try {
    try {
      runCodeThatMayThrowAnException();
    } catch (e) {
        // I'm handing the exception here (displaying a nice message or whatever)
        // Now I want to rethrow the exception
        throw (e);
    }
} catch (e) {
    // The stacktrace was lost here :(
}

Is there any way to keep the stacktrace? A jQuery plug-in maybe? Any workaround or ideas?

like image 781
rcarrillopadron Avatar asked Jan 25 '12 16:01

rcarrillopadron


People also ask

Is it possible to rethrow a caught exception?

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.

Is it possible to rethrow a caught exception Java?

If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What does it mean to Rethrow an exception?

Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

What is exception StackTrace?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.


1 Answers

In the final catch block try

    throw e.stack;

And I mean the very last one (the one going to the browser). If you nest your try/catch deeper, you'd need to change your previous throws.

    function throwError() {
        var test = _undefined.propertyAccess;
    }
    try {
        try {
            try {
                throwError();
            } catch (e) {
                alert("exception: " + e.stack);
                throw e;
            }
        } catch (e) {
            console.log(e.stack);
            throw e;
        }
    } catch (e) {
        throw e.stack;
    }

What an odd bug.

like image 142
Zach Avatar answered Sep 30 '22 15:09

Zach