Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rethrow an exception in Javascript, but preserve the stack?

People also ask

Can you Rethrow an exception?

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.

When should you Rethrow an 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.

What type of statement is used to Rethrow an exception?

A Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the exception currently being handled by the Catch statement. The Throw statement resets the call stack for the expression exception.


This is a bug in Chrome. Rethrowing an exception should preserve the call trace.

http://code.google.com/p/chromium/issues/detail?id=60240

I don't know of any workaround.

I don't see the problem with finally. I do see exceptions silently not showing up on the error console in some cases after a finally, but that one seems to be fixed in development builds.


The stack property of an Error object is created at the same time as the Error object itself, not at the point it's thrown. They're often the same because of the idiom

   throw new Error("message");

and if you use the code just as you've written it, the stack property will not be changed when you rethrow the error.


As mentioned, the stack is a snapshot created while running new Error(...), so you can't really throw the error with the same stack.

A workaround I used is to console.error the stack before throwing:

  console.error(err.stack);
  throw err;

It's not perfect, but it gets you enough debug-able information, and the stack of the original error.