Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Custom error subclasses and instanceof in JavaScript

34 Error subclasses that survive instanceof

fair

Build a two-level error hierarchy and route a handler by instanceof. Then find the trap in the version that forgets this.name, and check which of an error's fields are actually enumerable.

Stuck? Three hints, smallest first
  1. 1. super(message, options) forwards both, so a subclass supports cause for free.
  2. 2. Error.prototype.toString reads this.name, so forgetting to set it makes every subclass introduce itself as Error.
  3. 3. Assigning this.name creates an own, enumerable property. message is never one.

The answer

class PaymentError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = 'PaymentError';
  }
}

class InsufficientFunds extends PaymentError {
  constructor(shortfall, options) {
    super(`short by ₦${shortfall}`, options);
    this.name = 'InsufficientFunds';
    this.shortfall = shortfall;
  }
}

class Bare extends Error {}                    // the trap: no name assigned

const err = new InsufficientFunds(1500);
const chain = [
  err instanceof InsufficientFunds,
  err instanceof PaymentError,
  err instanceof Error,
  err instanceof TypeError,
];

const handle = (e) => {
  if (e instanceof InsufficientFunds) return 'top up ₦' + e.shortfall;
  if (e instanceof PaymentError) return 'payment problem: ' + e.message;
  return 'not ours: ' + e.name;
};
const routed = [handle(err), handle(new PaymentError('card declined')), handle(new RangeError('out of range'))];

const bare = new Bare('printer offline');
const survivesRejection = await Promise.reject(err).catch((e) => e instanceof InsufficientFunds);
const wrapped = new PaymentError('could not take payment', { cause: bare });

console.log('description :', String(err));
console.log('routed      :', routed);
console.log('the trap    :', bare.name, '/', String(bare), '/ but constructor:', bare.constructor.name);
console.log('own keys    :', Object.keys(err));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the whole prototype chain is intact', chain, [true, true, true, false]);
test('so instanceof is enough to route the handler', routed, ['top up ₦1500', 'payment problem: card declined', 'not ours: RangeError']);
test('name and message compose into the description', String(err), 'InsufficientFunds: short by ₦1500');
test('a subclass that forgets this.name introduces itself as Error', [bare.name, String(bare)], ['Error', 'Error: printer offline']);
test('though its constructor still knows what it is', bare.constructor.name, 'Bare');
test('assigning name makes it an own key; message never is one', Object.keys(err), ['name', 'shortfall']);
test('instanceof survives a trip through a rejected promise', survivesRejection, true);
test('and the subclass forwards cause to Error for free', wrapped.cause.message, 'printer offline');

Subclassing Error works properly in ES6 classes, and the first two assertions are the payoff: instanceof gives you dispatch, so a handler branches on the kind of failure instead of matching on message text. Message matching is the thing this replaces — messages get reworded, translated and interpolated, and every if (e.message.includes(‘declined’)) is a bug waiting for a copy edit.

this.name is the part everyone forgets. It is not decorative: toString, and therefore every default log line and every console.error, reads it. A hierarchy of five error classes that all announce themselves as Error is a hierarchy you cannot read in production, even though instanceof still works perfectly in code. this.constructor.name is the fallback that needs no assignment, and it is also what breaks first under a minifier.

The enumerability assertion is a preview of exercise 42. name is an own key because you assigned it; shortfall likewise; message and stack are inherited or non-enumerable, so they vanish from Object.keys, from a spread and from JSON.stringify. That single fact explains most "the error logged as {}" reports.

One older trap worth knowing: transpiled down to ES5, extends Error loses the prototype and instanceof silently returns false, which is why old code carries Object.setPrototypeOf(this, new.target.prototype). Native classes need none of that.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.