JavaScriptFundamental (ES6), part 1
Custom error classes and error.cause in JavaScript
131 error subclasses, and the cause chain
fairBuild a small hierarchy — AppError, then ValidationError and PaymentError under it — where each subclass reports its own name and carries its own extra field. Wrap a low-level failure in a PaymentError using { cause }, walk the chain from the outside in, and find out what JSON.stringify keeps of an error.
Stuck? Three hints, smallest first
- 1.
this.name = new.target.namein the base constructor gives every subclass the right name without repeating it. - 2. The second argument to
Erroris an options object:super(message, { cause }). Forget to forward it and the cause is gone. - 3. To walk the chain, follow
error.causeuntil it is undefined.
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = new.target.name;
}
}
class ValidationError extends AppError {
constructor(field, message, options) {
super(message, options);
this.field = field;
}
}
class PaymentError extends AppError {
constructor(reference, message, options) {
super(message, options);
this.reference = reference;
}
}
class Careless extends Error {
constructor(message, options) {
super(message);
this.name = 'Careless';
}
}
const chargeCard = () => { throw new RangeError('gateway timed out after 30s'); };
const takePayment = (reference) => {
try {
return chargeCard();
} catch (cause) {
throw new PaymentError(reference, 'could not charge the card', { cause });
}
};
const chainOf = (error) => {
const names = [];
let at = error;
while (at) {
names.push(`${at.name}: ${at.message}`);
at = at.cause;
}
return names;
};
const toPlain = (error) => ({
name: error.name,
message: error.message,
...(error.cause ? { cause: toPlain(error.cause) } : {}),
});
let caught = new Error('never thrown');
try { takePayment('TX-2019'); } catch (e) { caught = e; }
const kinds = [caught instanceof PaymentError, caught instanceof AppError, caught instanceof Error];
const sibling = new ValidationError('phone', 'phone must be 11 digits');
const careless = new Careless('lost the trail', { cause: new Error('the real problem') });
const serialised = JSON.stringify(caught);
console.log('caught :', caught.name, '|', caught.message);
console.log('chain :', chainOf(caught));
console.log('json :', serialised);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the subclass is recognised at every level of the hierarchy', kinds, [true, true, true]);
test('and reports its own name without each class repeating it', [caught.name, sibling.name], ['PaymentError', 'ValidationError']);
test('each subclass keeps the field that makes it useful', [caught.reference, sibling.field], ['TX-2019', 'phone']);
test('cause holds the original failure, untouched', [caught.cause.name, caught.cause.message], ['RangeError', 'gateway timed out after 30s']);
test('so the chain reads from the outside in', chainOf(caught), ['PaymentError: could not charge the card', 'RangeError: gateway timed out after 30s']);
test('a sibling subclass is not the same type', sibling instanceof PaymentError, false);
test('stringify keeps only the enumerable properties: message and stack vanish', serialised, '{"name":"PaymentError","reference":"TX-2019"}');
test('so serialising needs doing by hand, and it can carry the chain', toPlain(caught), { name: 'PaymentError', message: 'could not charge the card', cause: { name: 'RangeError', message: 'gateway timed out after 30s' } });
test('a constructor that forwards only the message throws the cause away', careless.cause, undefined);
Typed errors let a caller decide by instanceof instead of matching on message text. A ValidationError becomes a 422 and a form, a PaymentError becomes a retry and a reference to quote support — and both are still Errors, so a generic handler at the top still catches them.
cause is the standard way to wrap without losing. The alternative habits both cost you something: rethrowing the original keeps the detail and loses your context, and throwing a fresh error keeps your context and loses the detail. { cause } keeps both, and the chain walk above is the log line worth printing. The catch is the last assertion: cause only arrives if the constructor forwards its options to super, and a subclass that takes (message) alone silently drops it.
new.target.name is the small trick that keeps the base class honest — every subclass gets the right name with no extra line. Note the side effect it has on serialisation: name becomes an own enumerable property, so it survives JSON.stringify while message and stack, which are non-enumerable, do not. An error crossing a network boundary needs an explicit projection like toPlain, or it arrives as a nearly empty object.