How to extend error in JavaScript with ES6 syntax?

Sometimes, we want to extend error in JavaScript with ES6 syntax.

In this article, we’ll look at how to extend error in JavaScript with ES6 syntax.

How to extend error in JavaScript with ES6 syntax?

To extend error in JavaScript with ES6 syntax, we can use the extends keyword.

For instance, we write

class ExtendableError extends Error {
  constructor(message) {
    super();
    this.message = message;
    this.stack = new Error().stack;
    this.name = this.constructor.name;
  }
}

to create the ExtendableError class which inherits from the Error class.

In the constructor, we call super to initialize the parent constructor.

Then we add the instance properties for the constructor instance with the next 3 lines.

Conclusion

To extend error in JavaScript with ES6 syntax, we can use the extends keyword.