To throw errors in our JavaScript apps, we usually through an object that’s the instance of the Error
constructor.
In this article, we’ll look at how to extend the JavaScript Error
constructor with our own constructor.
Create Our Own Constructor Function
One way to extend the built-in Error
constructor is to create our own constructor that gets data from the Error
constructor.
For instance, we can write:
function MyError(message) {
this.name = 'MyError';
this.message = message;
this.stack = (new Error()).stack;
}
MyError.prototype = new Error();
throw new MyError('error occurred')
We create the MyError
constructor that takes the message
parameter.
We set message
as the value of the message
property.
And we get the stack trace from the stack
property of the Error
instance.
We set MyError.prototype
to a new Error
instance so that a MyError
instance is also an Error
instance.
In the constructor, we set the name
which will be logged when an error is thrown.
Then we throw a MyError
instance with the throw
keyword.
Once the error, is thrown, we should see it in the log.
And if we log myError instanceof Error
and myError instanceof MyError
, we should see that both are true
since we set MyError.prototype
to a new Error
instance.
Use the Class Syntax and extends Keyword to extend the Error Constructor
The class syntax is added to ES6 so that we can create constructors that inherit constructors easily.
However, underneath the syntactic sugar, prototypical inheritance is still used as we have in the previous example.
To extend the Error
constructor, we write:
class MyError extends Error {
constructor(message) {
super(message);
this.name = 'MyError';
}
}
const myError = new MyError('error occurred')
console.log(myError instanceof Error)
console.log(myError instanceof MyError)
throw myError
We create the MyError
class with the extends
keyword to create a subclass of the Error
class.
The constructor
takes the message
parameter and we pass that into the Error
constructor by calling super
.
We also set our own name
property in the constructor.
And then we instantiate the MyError
class the same way as before.
And if we use the instanceof
operator on Error
and MyError
, we see that they’re both true
.
When we throw an error, we see the message as we did before.
Conclusion
We can use regular prototypical inheritance or the class syntax to create our own constructor that inherits data from the Error
constructor.