Sub topic 6
Building an Error Hierarchy
This chapter assumes you can already write a custom error class that calls super(message, options) and sets this.name. It also assumes you know how to add structured fields such as status to that class. Here you will combine those pieces into a small family of related error classes.
Why group errors into a hierarchy
An error hierarchy is a set of error classes where general classes sit at the top and more specific classes extend them. Each level answers a different question:
Errortells you something failed.HttpErrortells you an HTTP request failed and carries the status code.NotFoundErrortells you exactly which kind of HTTP failure happened.
Code that handles errors can then pick the level it needs. A retry helper might only care that a failure was an HttpError. A UI layer might show a special message only for NotFoundError.
A base class with a shared field
The base class defines what every member of the family has in common. In this example, every HTTP failure has a status code.
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource, options) {
super(404, `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
class UnauthorizedError extends HttpError {
constructor(options) {
super(401, 'Authentication required', options);
this.name = 'UnauthorizedError';
}
}
const err = new NotFoundError('User 42');
console.log(err.status); // 404
console.log(err.message); // 'User 42 not found'
console.log(err instanceof NotFoundError); // true
console.log(err instanceof HttpError); // true
console.log(err instanceof Error); // true
console.log(String(err)); // 'NotFoundError: User 42 not found'The subclasses follow a few rules:
- They fix the shared fields.
NotFoundErroralways passes404, so callers cannot create a "not found" error with status 500 by mistake. - They build their own message. Callers pass the resource name, and the class formats the text. This keeps messages consistent across the codebase.
- They forward
options. Passingoptionsall the way up toErrorkeepscausesupport at every level. - They set
nameagain. Without this line, aNotFoundErrorwould report itself asHttpErrorin stack traces and inString(err).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Forgetting to reassign `name` in a subclass | Logs show the parent's name | Set `this.name` in every class |
| Dropping `options` in a subclass constructor | `cause` is silently lost | Accept `options` and pass it to `super` |
| Deep trees (four or more levels) | Hard to remember which class to throw or catch | Keep two or three levels |
| One class per call site | Hierarchy grows without adding meaning | Add a class only when callers will handle it differently |
Keeping the hierarchy small
Start with one base class per domain, such as HttpError, DatabaseError, or ValidationError. Add subclasses only as real handling needs appear. The next chapter shows how catch blocks use instanceof to choose between these levels.
Exercise
Add a RateLimitError class to the hierarchy above. It should have status 429, the message "Too many requests", and a retryAfter field in seconds that the caller supplies. Make sure cause still works.
Show answer
class RateLimitError extends HttpError { constructor(retryAfter, options) { super(429, 'Too many requests', options); this.name = 'RateLimitError'; this.retryAfter = retryAfter; } } // new RateLimitError(30, { cause: upstreamErr }) has status 429, retryAfter 30, and the cause.
Exercise
A teammate writes class ForbiddenError extends HttpError { constructor() { super(403, 'Forbidden'); } }. Name two problems with it.
Show answer
It never sets this.name, so it reports itself as "HttpError". It also accepts no options and passes none to super, so callers cannot attach a cause.