Sub topic 14
Subclassing Error and Other Built-ins
Built-in classes such as Error, Array, Map, and Set can be extended with extends like any class you write yourself. The subclass inherits the built-in's internal behavior: the stack trace on an error, the auto-updating length on an array, the hash table inside a map. This chapter covers what you get from that, how to set it up correctly, and the gotchas specific to built-ins.
This chapter assumes you already know extends, super(), instanceof, private fields, and how fields are initialized relative to the constructor.
Custom Error Types
Throwing plain Error objects forces the catching code to parse message strings to work out what went wrong. A custom error class gives each failure a type that catch blocks can check with instanceof, and it lets the error carry structured data.
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'
}Here is what each line does:
super(message)runs theErrorconstructor. That constructor setsmessageand, in every major engine, capturesstack. Skipping it is aReferenceError, the same as in any derived class.this.name = 'ValidationError'matters becausenameis inherited fromError.prototype, where its value is'Error'. Without this line, stack traces andString(err)would printError: Invalid email address, which hides the real type.this.fieldis ordinary extra data. Add whatever the handler needs, such as a field name, an HTTP status, or a retry hint.
The resulting prototype chain looks like this:
A Base Class for an Error Hierarchy
Most applications end up with several error types. A shared base class can set name automatically and pass the standard cause option through:
class AppError extends Error {
constructor(message, options) {
super(message, options); // forwards { cause } (ES2022)
this.name = this.constructor.name;
}
}
class NotFoundError extends AppError {
constructor(resource, options) {
super(`${resource} not found`, options);
this.resource = resource;
}
}
class DatabaseError extends AppError {}
try {
try {
throw new Error('connection reset');
} catch (low) {
throw new DatabaseError('Query failed', { cause: low });
}
} catch (err) {
console.log(err.name); // 'DatabaseError'
console.log(err.cause.message); // 'connection reset'
console.log(err instanceof AppError); // true
}
const nf = new NotFoundError('User 42');
console.log(nf.name, nf.message); // 'NotFoundError' 'User 42 not found'this.constructor.name reads the name of the class that new was called on, so each subclass gets the right name without repeating a string. The cause option attaches the original error. You keep the low-level details for debugging while throwing a higher-level error that makes sense to the caller.
Stack Trace Polish in V8
In Node.js and Chromium, Error.captureStackTrace(this, SomeFunction) rebuilds the stack and leaves out frames at and above SomeFunction. Subclasses already get correct stacks without it. It is only useful for hiding factory or helper functions from the trace, and because it is V8-specific you should guard the call:
function fail(message) {
const err = new Error(message);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(err, fail); // stack starts at fail's caller
}
return err;
}
console.log(fail('boom').stack.includes('at fail')); // false in V8Extending Array
An Array subclass keeps the array's special length behavior and gains your methods:
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
const s = Stack.from([1, 2, 3]);
s.push(4);
console.log(s.peek()); // 4
console.log(s.length); // 4
const doubled = s.map((x) => x * 2);
console.log(doubled instanceof Stack); // true
console.log(doubled.peek()); // 8Stack.from and Stack.of return Stack instances because the static methods are inherited and use this as the constructor. Methods that create a new array, such as map, filter, slice, and concat, also return a Stack. They do it through a mechanism called Symbol.species.
The Species Gotcha
When map needs a result array, it looks up this.constructor[Symbol.species] and calls new on it with a single argument: the length. That works only if your constructor accepts the same arguments as Array's. A custom signature breaks quietly:
class Tagged extends Array {
constructor(tag, ...items) {
super(...items);
this.tag = tag;
}
}
const t = new Tagged('nums', 1, 2, 3);
const m = t.map((x) => x * 2);
console.log(m.tag); // 3 (map called new Tagged(3))
console.log(m.length); // 3The fix is to tell derived methods to build plain arrays:
class Tagged extends Array {
static get [Symbol.species]() {
return Array;
}
constructor(tag, ...items) {
super(...items);
this.tag = tag;
}
}
const t = new Tagged('nums', 1, 2, 3);
const m = t.map((x) => x * 2);
console.log(m instanceof Tagged, Array.isArray(m)); // false trueThere is a second trap here: new Tagged('x', 5) calls super(5), and the Array constructor reads one numeric argument as a length. The result is an empty array of length 5, not [5]. To keep the items safe, call super() with no arguments and then this.push(...items).
Extending Map and Set
Map and Set subclasses work well for adding domain behavior. A map that fills in missing keys is a common example:
class DefaultMap extends Map {
#factory;
constructor(factory, entries) {
super(entries);
this.#factory = factory;
}
get(key) {
if (!this.has(key)) {
this.set(key, this.#factory(key));
}
return super.get(key);
}
}
const groups = new DefaultMap(() => []);
groups.get('fruit').push('apple');
groups.get('fruit').push('pear');
console.log(groups.get('fruit')); // ['apple', 'pear']
console.log(groups.size); // 1Overridden Methods Run Inside super()
The Map constructor adds the initial entries by calling this.set, and Set does the same with this.add. If you override that method, your override runs during super(). At that point your class fields and private fields have not been installed yet:
class LoggedMap extends Map {
#log = [];
set(key, value) {
this.#log.push(key);
return super.set(key, value);
}
}
new LoggedMap([['a', 1]]);
// TypeError: Cannot read private member #log from an object whose class did not declare itThe fix is to call super() with no entries and add them yourself after the fields exist:
class LoggedMap extends Map {
#log = [];
constructor(entries = []) {
super();
for (const [key, value] of entries) {
this.set(key, value);
}
}
set(key, value) {
this.#log.push(key);
return super.set(key, value);
}
get log() {
return [...this.#log];
}
}
console.log(new LoggedMap([['a', 1], ['b', 2]]).log); // ['a', 'b']Failure Modes at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Stack trace says `Error:` instead of your type | `name` is inherited from `Error.prototype` | Set `this.name` in the constructor |
| `instanceof MyError` is false | Code compiled to ES5, where `Error.call(this)` returns a new object | Target ES2015 or later, or call `Object.setPrototypeOf(this, new.target.prototype)` |
| `map`/`filter` results have wrong extra properties | `Symbol.species` calls your constructor with a length | Return `Array` from `static get [Symbol.species]` |
| `new MyArray(5)` is empty | `Array` reads one number as a length | Use `super()` followed by `push` |
| Private field error in `Map`/`Set` subclass constructor | `super(entries)` calls your override before fields exist | Pass no entries to `super`, then add them yourself |
Exercise
A team's TypeScript project compiles with "target": "ES5". Their class HttpError extends Error throws correctly, but err instanceof HttpError is false in the catch block. Explain why and give a fix.
Show answer
In ES5 output, the class becomes a function that calls Error.call(this, message). Error ignores the this passed to it and returns a brand-new plain Error object, so the instance's prototype is Error.prototype and not HttpError.prototype. Either compile to ES2015 or later so that native class and super() are used, or add Object.setPrototypeOf(this, new.target.prototype) in the constructor right after super(message).
Exercise
Given class Row extends Array { constructor(id, ...cells) { super(...cells); this.id = id; } } and const r = new Row('r1', 'a', 'b'), what is r.filter(Boolean).id, and why?
Show answer
It is 0. filter creates its result through Symbol.species, which calls new Row(0) because the initial length is 0. That sets id to 0. Elements are then added to the new array one by one. Adding static get [Symbol.species]() { return Array; } makes filter return a plain array with no id.
Exercise
Write a UniqueList extends Set whose add throws a DuplicateError (a custom Error subclass carrying the duplicate value) when the value is already present, and whose constructor accepts an iterable of initial values.
Show answer
class DuplicateError extends Error { constructor(value) { super(Duplicate: ${value}); this.name = 'DuplicateError'; this.value = value; } } class UniqueList extends Set { constructor(values = []) { super(); for (const v of values) this.add(v); } add(value) { if (this.has(value)) throw new DuplicateError(value); return super.add(value); } } Calling super() with no values keeps the override from running before construction finishes, and new UniqueList([1, 1]) throws a DuplicateError whose value is 1.