Create Custom JavaScript Error Objects
In JavaScript, there’s an Error
class to let us throw exceptions. We can create custom error classes by extending the Error
class with our own class and custom logic to throw more specific errors.
The Error
class has the message
, name
, and stack
properties that we inherit from it. Of course, like any other class, we can define our own fields and methods inside it.
Create a New Error Class
For example, to make data validation easier, we can make a ValidationError
class which is thrown whenever our code encounters invalid data.
We can create a new class as follows:
class ValidationError extends Error {
constructor(message, type) {
super(message);
this.name = "ValidationError";
this.type = type;
}
}
As we can see, we used the extends
keyword to indicate that we want to inherit from the Error
class.
Using Error Classes we Defined
After we defined our error classes, we can use our ValidationError
class as follows:
try {
let data = {
email: 'abc'
}
if (!/[^@]+@[^\.]+\..+/.test(data.email)) {
throw new ValidationError('invalid email', 'email error');
}
} catch (ex) {
console.log(ex);
}
In the console.log
output, we should see ‘ValidationError: invalid email’ when we run the code.
We can also log the message
, name
, stack
, and type
properties individually:
try {
let data = {
email: 'abc'
}
if (!/[^@]+@[^\.]+\..+/.test(data.email)) {
throw new ValidationError('invalid email', 'email error');
}
} catch (ex) {
const {
message,
name,
stack,
type
} = ex;
console.log(
message,
name,
stack,
type
);
}
Then we should see:
invalid email
logged formessage
ValidationError
logged forname
ValidationError: invalid email
for
at window.onloadstack
email error
logged fortype
As with another type of object, we can use the instanceof
operator to check if it’s an instance of ValidationError
as follows: