Custom error classes
Learn to create your own error class by extending Error.
Custom error classes
You create your own error type by using extends on JavaScript's built-in Error class. In the subclass constructor you pass the message up with super and set this.name to the class name. This lets you tell errors apart by type and handle each one differently.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}The class ... extends Error syntax here creates a new error type based on Error; you will cover classes in detail at the advanced level. For now it is enough to use this pattern as is.
Throwing a custom error
After defining the custom error class you throw it with throw new ValidationError('...'). Unlike throwing a plain Error, this makes the error's type explicit so the catching side can react accordingly. The thrown error travels up the call chain until a matching catch block handles it.
function validateEmail(email) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email');
}
} Exercise Write the ValidationError class
Write an error class called ValidationError. It should extends the Error class. Its constructor takes a message parameter, calls super(message) and sets this.name to the string 'ValidationError'.
Show example solution
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
Test yourself
-
Why call super in a custom error class?
- To pass the message to the Error class
- To throw the error
- To freeze the class
- To make it async
Show answer
To pass the message to the Error class — Correct! super(message) passes the message to the Error class.
-
Extend the class from Error
class ValidationError ____ { constructor(message) { super(message); this.name = 'ValidationError'; } }Show answer
class ValidationError extends Error { constructor(message) { super(message); this.name = 'ValidationError'; } } -
Match error properties to their meanings
- name
- Error type label
- message
- Description text
- stack
- Call stack trace