Sub topic 6
Building an Error Hierarchy
A single custom error class can tell you that a failure came from your code and not from the runtime. Once an application has more than a handful of failure modes, you usually want something more: groups of related errors that callers can handle together or separately, depending on how much they care. An error hierarchy gives you those groups. It is a set of error classes connected by extends, where each level adds or pins down information.
This chapter assumes you can already subclass Error, set name in the constructor, and add structured fields such as status. It also assumes you know how super works in derived class constructors. Selective handling in catch blocks with instanceof comes in the next chapter. Here the focus is designing and building the classes.
Why group errors at all
The reason is that callers react to failures at different levels of detail:
- A generic HTTP middleware only needs to know "this is an HTTP error with a status code" so it can send the right response.
- A route handler may want to treat "not found" differently from "unauthorized", for example by showing a friendly 404 page.
- A top-level crash handler only needs to know "this is one of ours" versus "this is a bug or a runtime failure".
With a hierarchy, each caller checks against the class that matches its level of interest. A check against a base class matches every subclass under it, so adding a new subclass later does not break the general handlers.
A two-level hierarchy
The most common shape is a base class that adds a structured field and subclasses that fix that field to a specific value.
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';
}
}
const err = new NotFoundError('User 42');
console.log(err.status); // 404
console.log(err instanceof HttpError); // true
console.log(err.message); // 'User 42 not found'Notice how each level divides the work:
HttpErrorowns thestatusfield. It accepts any status, so code that has a raw status code from a response can use it directly.NotFoundErrorhides the status from its callers. It takes a resource description, builds the message itself, and always passes404. Callers can't build aNotFoundErrorwith the wrong status.- Both constructors forward
optionstosuper, so acausepassed at the bottom reaches theErrorconstructor at the top.
How the constructor chain runs
When you call new NotFoundError('User 42'), the constructors run in this order:
NotFoundError's constructor starts.thisis not yet usable.- It calls
super(404, 'User 42 not found', undefined), which runsHttpError's constructor. HttpErrorcallssuper(message, options), which runsError.Errorcreates the object withNotFoundError.prototypeas its prototype and setsmessageandstack.- Back in
HttpError,nameis set to'HttpError'andstatusto404. - Back in
NotFoundError,nameis overwritten with'NotFoundError'.
The last step matters. Each level assigns name, and the most-derived constructor runs last, so its value is the one that sticks.
Growing the hierarchy
Adding a sibling follows the same pattern. Here the subclasses take an optional message with a sensible default:
class UnauthorizedError extends HttpError {
constructor(message = 'Authentication required', options) {
super(401, message, options);
this.name = 'UnauthorizedError';
}
}
class ForbiddenError extends HttpError {
constructor(message = 'Access denied', options) {
super(403, message, options);
this.name = 'ForbiddenError';
}
}
const errors = [
new UnauthorizedError(),
new ForbiddenError('Admins only'),
new HttpError(500, 'Internal error'),
];
for (const e of errors) {
console.log(`${e.name} ${e.status}: ${e.message}`);
}
// UnauthorizedError 401: Authentication required
// ForbiddenError 403: Admins only
// HttpError 500: Internal errorCode that turns a raw response into an error often needs a factory that picks the most specific class available and falls back to the base class:
function httpErrorFromStatus(status, message, options) {
switch (status) {
case 401:
return new UnauthorizedError(message, options);
case 403:
return new ForbiddenError(message, options);
case 404:
return new NotFoundError(message ?? 'Resource', options);
default:
return new HttpError(status, message ?? `HTTP ${status}`, options);
}
}
const e = httpErrorFromStatus(403);
console.log(e instanceof ForbiddenError, e.status); // true 403The factory keeps the mapping in one place. Without it, every call site would repeat its own status-to-class logic.
A shared application root
Many codebases put one more class above everything they define, often called AppError. It answers the top-level question "is this an error we threw on purpose?" It can also hold behavior that every error shares. A common example is setting name automatically:
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = new.target.name;
}
}
class PaymentError extends AppError {}
class CardDeclinedError extends PaymentError {
constructor(reason, options) {
super(`Card declined: ${reason}`, options);
this.reason = reason;
}
}
const err = new CardDeclinedError('insufficient funds');
console.log(err.name); // 'CardDeclinedError'
console.log(err instanceof PaymentError); // true
console.log(err instanceof AppError); // truenew.target refers to the class that new was called on, even inside a parent constructor. So new.target.name is the name of the most-derived class. Subclasses that add nothing, like PaymentError, then need no constructor at all.
Common mistakes
Forgetting to set name in a subclass
When a subclass doesn't assign name, it inherits the value its parent's constructor assigned:
class BadRequestError extends HttpError {
constructor(message, options) {
super(400, message, options);
// name not set
}
}
const e = new BadRequestError('Missing id');
console.log(e.name); // 'HttpError'
console.log(String(e)); // 'HttpError: Missing id'instanceof BadRequestError still works, but logs and stack traces show the wrong class, which makes debugging slower. Use the AppError pattern above or add a lint rule for this.
Dropping options along the chain
If any constructor in the chain doesn't forward options, the cause is silently lost for every class below it. Check each level, especially subclasses with a different signature from their parent.
Changing the constructor signature without a reason
HttpError takes (status, message, options), but NotFoundError takes (resource, options). That difference is deliberate, because the subclass fixes the status and builds the message. Different signatures make the classes harder to use interchangeably, though, so document each one and keep options as the last parameter everywhere.
How deep and how wide
| Level | Example | Typical catcher |
|---|---|---|
| Application root | `AppError` | Top-level crash handler, logger |
| Category | `HttpError`, `PaymentError`, `ValidationError` | Middleware, service boundary |
| Specific case | `NotFoundError`, `CardDeclinedError` | The caller that can recover from it |
Some rules of thumb:
- Two or three levels below
Erroris usually enough. Deeper trees are hard to remember and rarely match how callers actually make decisions. - Group classes by how callers react, not by which module throws them.
NotFoundErrorfrom the user service and from the order service should be the same class, because a caller handles them the same way. - Add a subclass only when some caller will handle it differently, or when it carries different fields. Otherwise, an extra field on the parent (for example a
codestring) is cheaper. The final chapter compares these two approaches in more detail.
Exercise
You add class ConflictError extends HttpError { constructor(message, options) { super(409, message, options); } } with HttpError defined as in this chapter. What do new ConflictError('Email taken').name and String(new ConflictError('Email taken')) return, and how do you fix it?
Show answer
name is 'HttpError' and the string is 'HttpError: Email taken', because the subclass never overwrites the name that HttpError's constructor assigned. Fix it by adding this.name = 'ConflictError'; after the super call, or by deriving from a base class that sets this.name = new.target.name.
Exercise
A teammate proposes UserNotFoundError, OrderNotFoundError, and ProductNotFoundError as separate subclasses of HttpError. When is that a good idea, and what is the usual alternative?
Show answer
It is only worth it if callers handle those cases differently or the classes carry different fields. Usually they are all handled the same way (respond with 404), so one NotFoundError that takes the resource as an argument is simpler. A field such as resource can hold the distinguishing detail without adding classes.
Exercise
In the AppError example, PaymentError has no constructor. Why does new PaymentError('Gateway timeout', { cause: err }) still have the correct name and keep the cause?
Show answer
A derived class with no constructor gets a default one that passes all arguments to super. So AppError's constructor receives the message and options and forwards both to Error, which creates the cause property. It then sets name from new.target.name, and new.target is PaymentError.