Create Custom JavaScript Error Objects

John Au-Yeung
Level Up Coding
Published in
4 min readJan 29, 2020

Photo by mali desha on Unsplash

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 for message
  • ValidationError logged for name
  • ValidationError: invalid email
    at window.onload
    for stack
  • email error logged for type

As with another type of object, we can use the instanceof operator to check if it’s an instance of ValidationError as follows:

Read the full story with a free account.

The author made this story available to Medium members only.
Sign up to read this one for free.

Or, continue in mobile web

Already have an account? Sign in

Recommended from Medium

Lists

See more recommendations