7

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?

rcarrillopadron
  • 459
  • 2
  • 6
  • 19
  • Can I know why you chose to have two try...catch? – Grace Huang Jan 25 '12 at 18:39
  • First, because I need to display a nice message to the user in case one of the services are not available. Crashing is not an option. Second, because I need to send the content of the javascript exception somewhere to my backend to know exactly what happened. Maybe it's a bug and I want to fix it before the customer calls me saying that the site is not working. – rcarrillopadron Jan 27 '12 at 18:33
  • But why one level of try...catch is not enough? Is it because you want to aggregate all the error messages? – Grace Huang Jan 27 '12 at 18:37
  • No it's because I'm adding more information to the exception. I don't want to end with an exception message saying: "value is NaN". I want to have a more descriptive exception like "The amount returned from the server for invoiceId 123 is equals to 'abc' and cannot be considered as a number." – rcarrillopadron Jan 27 '12 at 18:46

1 Answers1

5

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.

Zach
  • 76
  • 2