How do you build a custom error class?
You build a custom error class by extending the built-in Error class. Inside the constructor you call the parent constructor with your message, and then you set the name property so that the error identifies itself properly in your logs and in your catch blocks.
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.isValidationError = true;
}
}
try {
throw new ValidationError('email', 'That address is not valid');
} catch (err) {
console.log('is an Error:', err instanceof Error);
console.log('is a ValidationError:', err instanceof ValidationError);
console.log('name:', err.name);
console.log('field:', err.field);
console.log('message:', err.message);
}
The call to the parent constructor is not optional. The Error constructor sets up the message and the stack trace, so if you skip it your error will have no useful message and no stack trace at all. You also have to call it first, before you touch this, because the language requires that when you extend a built-in class.
Setting the name matters because that is the property that your catch block and your log formatter read. The name on the Error prototype is inherited as Error, so a subclass that does not set it will be reported as a plain Error, and you lose the ability to tell your error types apart while the program is running.
The extra properties are your own data about the problem. The field in this example is what makes the error useful inside a form handler, where you can place the message next to the right input box. You can also add a status code, a machine-readable code, or a list of problems, and then your catch block can decide what to do based on those values instead of matching the text of the message.