Sub topic 14
Subclassing Error and Other Built-ins
This chapter assumes you already know how extends creates a subclass and how super() calls the parent constructor. Here you apply both to classes the language provides, mainly Error and Array.
Why subclass Error
A plain throw new Error('...') tells the caller that something failed, but it doesn't say what kind of failure it was. If you create your own error types, catch blocks can branch on the type and read extra fields. Your errors still keep the message, the stack trace, and normal instanceof behavior.
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
throw new ValidationError('email', 'Invalid email address');
} catch (err) {
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
console.log(err.name, err.field, err.message); // 'ValidationError' 'email' 'Invalid email address'
}There are three details to get right:
- Pass the message to
super(). TheErrorconstructor setsmessageand records the stack. If you assignthis.messageyourself afterward, the code works, but you skip the built-in handling. - Set
name. Otherwise it falls back to'Error', which is the name you see in stack traces and inString(err). - Add fields only after
super().thisdoesn't exist until the parent constructor has run.
A reusable base error with cause
If you have many error types, put the shared setup in one base class. You can set name from this.constructor.name, which saves each subclass from repeating it. Passing an options object through to super() keeps the standard cause property, which links a new error to the error that triggered it. cause is supported in Node 16.9+ and current browsers.
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = this.constructor.name;
}
}
class NotFoundError extends AppError {}
try {
try {
JSON.parse('{bad json');
} catch (inner) {
throw new NotFoundError('Config not found', { cause: inner });
}
} catch (err) {
console.log(err.name); // 'NotFoundError'
console.log(err.cause instanceof SyntaxError); // true
}Subclassing Array and other built-ins
Map, Set, Array, and Promise can all be extended the same way. Arrays have one extra behavior to know about: methods such as map and filter return an instance of your subclass, not a plain array.
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
const s = new Stack();
s.push(1, 2, 3);
console.log(s.peek()); // 3
console.log(s.length); // 3
const doubled = s.map((n) => n * 2);
console.log(doubled instanceof Stack); // true
console.log(doubled.peek()); // 6This works because map uses Symbol.species to decide which constructor builds the result. Two common mistakes follow from that:
| Pitfall | What happens | Fix |
|---|---|---|
| Constructor with a custom signature | `map` calls `new Stack(length)` and passes your constructor the wrong arguments | Keep the `Array` signature, or override `static get [Symbol.species]() { return Array; }` |
| `new Stack(3)` | Creates an empty array of length 3, not `[3]` | Create the stack empty and then use `push`, or use `Stack.of(3)` |
Exercise
You write class HttpError extends Error { constructor(status, message) { this.status = status; super(message); } }. What goes wrong, and how do you fix it?
Show answer
Assigning this.status before super() throws a ReferenceError, because this is not initialized until the parent constructor has run. Call super(message) first, then set this.status = status and this.name = 'HttpError'.
Exercise
Why might filter on an Array subclass break if its constructor is constructor(name) { super(); this.name = name; }?
Show answer
filter builds its result through Symbol.species, so it calls the subclass constructor with a length argument instead of a name. That assigns the wrong value to name. Override static get [Symbol.species]() { return Array; } so derived arrays are plain arrays, or keep the constructor compatible with Array.