Geoff
Geoff

Reputation: 4632

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

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 :)

Upvotes: 228

Views: 108216

Answers (5)

Ryan Wheale
Ryan Wheale

Reputation: 28380

I usually create my own custom error class for doing this and have just brought it around with me wherever I go. It ends up being useful and I use this in almost every app I build these days:

NOTE: this preserves the original error message/stack.

class AppError extends Error {
  constructor(messageOrError: string | Error) {
    const isError = messageOrError instanceof Error;
    super(isError ? messageOrError.message : messageOrError);
    
    if (isError) {
      this.stack = messageOrError.stack;
      this.cause = messageOrError;
    }
    
    // you can do some logging here to save on boilerplate
    if (process.env.NODE_ENV === 'production') {
        log(this.message);
    } else {
        log(this.stack);
    }

  }
}

You can throw the original error/stack like this:

try {
  ...
} catch(err) {
  // do stuff
  throw new AppError(err);
}

You can also check for this error and handle it differently:

if (err instanceof AppError) {
  ...
}

Upvotes: 2

texuf
texuf

Reputation: 511

Don't catch it in the first place, just use finally

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

Upvotes: -1

Ofer Segev
Ofer Segev

Reputation: 5282

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.

Upvotes: 10

Mike Stay
Mike Stay

Reputation: 1153

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.

Upvotes: 39

Glenn Maynard
Glenn Maynard

Reputation: 57464

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.

Upvotes: 105

Related Questions