What’s a good way to extend Error in JavaScript?

What's a good way to extend Error in JavaScript?

A good way to extend the Error class in JavaScript is to use the class keyword to create a new class that inherits from the Error class. This can be done using the extends keyword, like this:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}

In this example, MyError is a new class that inherits from the built-in Error class. The constructor function takes a message parameter, which is passed to the parent class’s constructor function using the super keyword. Additionally, the name property is set to ‘MyError’ which can be useful for identifying the error.

You can also set additional properties and methods in your custom error class as required.

Here’s an example of how you can use your custom error class

try {
  throw new MyError('Something went wrong');
} catch (err) {
  if (err instanceof MyError) {
    console.log(err.name); // MyError
    console.log(err.message); // Something went wrong
  }
}

It’s also a good practice to include a stack trace for debugging purpose by using the Error.captureStackTrace method.

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
    Error.captureStackTrace(this, MyError);
  }
}

Note that, in older version of javascript, Error.captureStackTrace is only supported in V8. So, you might not be able to use it in other javascript engines.

Leave a Reply