Home > OS >  How can i change the name or message of a JavaScript Error object?
How can i change the name or message of a JavaScript Error object?

Time:05-06

I have a JavaScript error object that I have caught in code. It has a name, message, stack etc that I want to log at the backend. I am using sentry for that. But before logging I want to change the name or the message of the error.

What will be the best way to do it? I tried creating a new error and adding the original error as cause, but that did not work with sentry. It just logs the error passed as the cause of the new error.

new Error('Additional error message', { cause: originalError });

I need the rest of the properties of the error to remain the same, just need to change the name or message.

CodePudding user response:

A super helpful thing you can do to accomplish this is actually create your own custom error types. This can be done by simply using a class that extends the Error constructor, like so:

class MyError extends Error {
  constructor(message) {
    super();
    this.name = "MyError";
    this.message = message;
  }
}
try {
  throw new MyError('this is my error')
} catch (err) {
  console.log(err instanceof Error);
  console.log(err.message);
  console.log(err.name);
  console.log(err.stack);
}

class ExtendedError extends Error {
  constructor(message, originalError) {
    super();
    this.name = "ExtendedError";
    this.message = message;
    this.originalError = {
      name: originalError.name,
      message: originalError.message,
      stack: originalError.stack
    };
  }
}
try {
  throw new Error('Something bad happened!');
} catch (err) {
  let extendedError = new ExtendedError('Additional details', err);
  console.log(extendedError instanceof Error);
  console.log(extendedError.message);
  console.log(extendedError.name);
  console.log(extendedError.originalError);
  console.log(extendedError.stack);
}

CodePudding user response:

You can create new Error with name and pass second argument as error object.

const originalError = new Error('Additional error message', { cause: 'root cause' });

const newError = new Error('different error', originalError);

console.log(newError.cause)
console.log(newError.toString())

  • Related