views:

65

answers:

1

In Javascript, suppose I want to perform some cleanup when an exception happens, but let the exception continue to propagate up the stack, eg:

try {
  enterAwesomeMode();
  doRiskyStuff(); // might throw an exception
} catch (e) {
  leaveAwesomeMode();
  throw e;
}
doMoreStuff();
leaveAwesomeMode();

The problem with this code is that catching and rethrowing the exception causes the stack trace information up to that point to be lost, so that if the exception is subsequently caught again, higher up on the stack, the stack trace only goes down to the re-throw. This sucks because it means it doesn't contain the function that actually threw the exception.

As it turns out, try..finally has the same behavior, in at least Chrome (that is, it is not the re-throw that is the problem precisely, but the presence of any exception handler block at all.)

Does anyone know of a way to rethrow an exception in Javascript but preserve the stack trace associated with it? Failing that, how about suggestions for other ways to add exception-safe cleanup handlers, while also capturing complete stack traces when an exception happens?

Thanks for any pointers :)

A: 

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

   throw new Error("message");

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

Mike Stay