Node.js
Custom errors
Learn to write your own Error-derived class.
Custom errors
Sometimes you want to tell the type of an error apart. A custom error is a subclass derived from the Error class. It is defined with class ValidationError extends Error.
In the subclass you write a constructor and call the parent's constructor with super(message). You also set the this.name property to the class name, so err.name returns "ValidationError". For example, you define separate classes to tell a validation error from a network error. You can also check the type with instanceof: err instanceof ValidationError. This keeps error management organized in complex apps.
constructor and super
In a custom error class, the constructor method must call the parent's constructor with super(message). This ensures message and stack are set correctly.
For example, class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } }. If super(message) is not called, this cannot be used; this throws a ReferenceError. If this.name is not set, the default "Error" stays, which makes telling types apart harder. instanceof still works, but you may also want to see the type as a string with name. So doing both is best.
Exercise Write a ValidationError class and catch it
Define a ValidationError class that extends Error. In constructor(message) set super(message) and this.name = "ValidationError". In try throw new ValidationError("invalid"), in catch (e) print console.log(e.name).
Show example solution
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("invalid");
} catch (e) {
console.log(e.name);
}
Test yourself
-
Match each piece to its role
- extends Error
- Derives from Error
- super(message)
- Calls the parent class
- this.name
- Sets the error type
- class
- Defines a new class
-
Why is this.name set in a custom error class?
this.name = "ValidationError"
- For memory
- To tell the error type apart
- It is unnecessary
- For performance
Show answer
To tell the error type apart — With name you tell the type of the error apart.
-
Derive with extends
class ValidationError ____ Error {}
Show answer
class ValidationError extends Error {}
Next lesson: Error middleware