Sub topic 6
Defining Your Own Error Classes
This chapter assumes you know the class syntax, including extends and super. It also assumes you have read the earlier chapters on Error objects, throw, and the built-in error types.
Built-in types such as TypeError and RangeError describe problems in the language itself. Your application has its own kinds of failure: a form field that fails validation, a record that does not exist, a payment the bank declines. A custom error class gives each of these failures a name. It can also carry the extra data that the code handling it needs.
The working model
A custom error class is a class that extends Error. Any instance of it is a real Error object. It has a message and a stack, and it can be thrown and caught like any other error. The subclass has three jobs:
- Call
super(message)so thatErrorsets upmessageandstack. - Set
this.nameso that logs and stack traces show the right type. - Store any extra fields that callers will need.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(age) {
if (!Number.isInteger(age) || age < 0) {
throw new ValidationError('Age must be a non-negative integer', 'age');
}
return age;
}
try {
validateAge(-1);
} catch (err) {
console.log(err.name); // 'ValidationError'
console.log(err.field); // 'age'
console.log(err.message); // 'Age must be a non-negative integer'
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
}The two instanceof checks both return true because the prototype chain runs ValidationError → Error → Object. The next chapter uses this to decide which errors a catch block should handle.
Building a small hierarchy
When an application defines several error types, a shared base class saves repetition. It also gives callers one type they can check for "any error from our code". Setting this.name = this.constructor.name in the base class gives each subclass the right name without extra code.
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = this.constructor.name;
}
}
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} ${id} not found`);
this.resource = resource;
this.id = id;
}
}
class ValidationError extends AppError {
constructor(message, field) {
super(message);
this.field = field;
}
}
const err = new NotFoundError('User', 42);
console.log(err.name); // 'NotFoundError'
console.log(err.message); // 'User 42 not found'
console.log(err instanceof AppError); // true
console.log(err.stack.split('\n')[0]); // 'NotFoundError: User 42 not found'The base constructor passes options on to Error. That keeps the cause option available, which a later chapter covers.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `this` before `super()` | `ReferenceError: Must call super constructor` | Call `super(message)` first |
| Not setting `name` | Logs show `Error: ...` instead of your type | Set `this.name`, or use `this.constructor.name` in a base class |
| Leaving out `message` | `message` is an empty string | Always pass a message that a person can read |
| Passing data only through the message | Callers have to parse strings to get it | Store the data as fields such as `field` or `id` |
| Not passing `options` to `super` | `cause` is lost | Write `super(message, options)` |
Exercises
Exercise
Write a RateLimitError class that extends Error. It should take a retryAfter value in seconds, set the message to Retry after N seconds, set name correctly, and keep retryAfter as a field.
Show answer
class RateLimitError extends Error { constructor(retryAfter) { super(Retry after ${retryAfter} seconds); this.name = 'RateLimitError'; this.retryAfter = retryAfter; } } Then new RateLimitError(30) has name 'RateLimitError', message 'Retry after 30 seconds', and retryAfter 30.
Exercise
A developer writes constructor(message, field) { this.field = field; super(message); }. What happens when this class is instantiated, and why?
Show answer
It throws a ReferenceError. In a derived class, this does not exist until super() has run, so the line this.field = field fails. Move super(message) to the top of the constructor.