Search code examples
javascriptnode.jserror-handlingsentrywinston

Can I re-create an error object with the original stack and stack frames?


I'm familiar with creating a custom Error object in JavaScript like this.

class CustomError extends Error {
  constructor(args) {
    super(...args);
    Error.captureStackTrace(this, CustomError);
  }
}

But given an exception/error that has already been thrown elsewhere I want to create a new error object that is a clone/copy of the original including the stack.

My context is that I'm using a log reporter, e.g. Winston, to capture events and I would like to post error messages to Sentry. Sentry provides a way to capture exceptions like this -

try {
    aFunctionThatMightFail();
} catch (err) {
    Sentry.captureException(err);
}

The problem though is that Sentry assumes that where the error is captured is where the error was thrown.

One of the benefits of Sentry is that it can report the line numbers of where the error occurred in an app but because I'm aggregating the logs the stack frame from the original error has been lost. I can save additional meta-data which I can send to Sentry but it still highlights the line with Sentry.captureException as the origin of the error and the stack frames from calling Winston.

enter image description here


Solution

  • The Sentry SDK assembles a JSON payload from the Error object you pass to captureException. I think you'll just want to assemble that payload directly and send it using captureEvent. See https://docs.sentry.io/development/sdk-dev/attributes/ for more information.