Create a custom error class in TypeScript
5 A ValidationException class of your own
easyWrite an error class extending the built-in Error, then throw and catch it with your own message.
Stuck? Three hints, smallest first
- 1. Call
super(message)first, then setthis.nameso logs read correctly. - 2. Carry structured data as extra fields, such as which field failed and what value arrived.
- 3. Catch by type with
instanceof, never by comparing message text.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class ValidationException extends Error {
constructor(
message: string,
public readonly field: string,
public readonly received: unknown,
) {
super(message);
this.name = 'ValidationException'; // this is what shows up in logs
}
}
interface Booking {
reference: string;
seats: number;
}
function validate(input: { reference?: string; seats?: number }): Booking {
if (typeof input.reference !== 'string' || input.reference.length === 0) {
throw new ValidationException('reference is required', 'reference', input.reference);
}
if (typeof input.seats !== 'number' || !Number.isInteger(input.seats) || input.seats < 1) {
throw new ValidationException('seats must be a whole number of 1 or more', 'seats', input.seats);
}
return { reference: input.reference, seats: input.seats };
}
function check(input: { reference?: string; seats?: number }): string {
try {
const booking = validate(input);
return `ok: ${booking.reference} x${booking.seats}`;
} catch (err) {
if (err instanceof ValidationException) {
return `${err.name} on "${err.field}": ${err.message} (got ${JSON.stringify(err.received)})`;
}
throw err;
}
}
console.log(check({ reference: 'BK-0001', seats: 2 }));
console.log(check({ seats: 2 }));
console.log(check({ reference: 'BK-0002', seats: 0 }));
test('a valid booking', check({ reference: 'BK-0001', seats: 2 }), 'ok: BK-0001 x2');
test('a missing reference names the field', check({ seats: 2 }).includes('on "reference"'), true);
test('a bad seat count names that field', check({ reference: 'BK-2', seats: 0 }).includes('on "seats"'), true);
test('it is still an Error', new ValidationException('x', 'f', 1) instanceof Error, true);
test('and it is its own type', new ValidationException('x', 'f', 1) instanceof ValidationException, true);
test('the name is set for logs', new ValidationException('x', 'f', 1).name, 'ValidationException');
Output
Three things make a custom error worth the five lines: instanceof lets a caller handle exactly this failure, the extra fields carry data a message cannot, and setting this.name means your log says ValidationException rather than the useless Error.