Ad space (banner)
🟨JavaScript Lessons
Lesson 26 / 69

Building a Custom Error Class

In this lesson you'll learn how to build a custom error class in JavaScript so you can clearly distinguish different kinds of errors. This is for people searching "JavaScript how to create a custom error" or "JavaScript Error extends."

Extending the Error class with extends lets you create your own "dedicated error." Giving each kind of error its own name makes it much easier to tell, when you catch it, what kind of problem actually occurred. If you can distinguish "invalid input error" from "network failure error," you can write code that responds appropriately to each (showing a specific message, retrying, and so on).

The sample code creates a class called ValidationError that inherits from Error, and sets its own name into this.name. Inside the checkAge function, when the age is invalid, it raises this error with throw new ValidationError(...), and the catch block checks e.name and e.message.

A common beginner stumbling block is forgetting to call super(message), which results in the error message not being set correctly. When building a custom error, just like normal class inheritance, you always need to call the parent class's (Error's) constructor. Also be careful not to create so many error classes that you lose track of what each one is for.

In real development, the larger an application gets, the more common it is to prepare a custom error class for each kind of error that can occur. Being able to vary how you log something or what message you show a user based on the error type makes this an important design technique for building maintainable error handling.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)