Handle errors at multiple levels in TypeScript
9 One fault, handled at three levels
hardRead data and handle failures at more than one level of your code, deciding at each level whether to deal with the fault or pass it up. Adapted: an in-memory store stands in for the file system.
Stuck? Three hints, smallest first
- 1. The rule: handle an error at the level that can actually do something about it.
- 2. A low level should add context and rethrow; only the top level should decide what the user sees.
- 3. Wrapping with
{ cause }keeps the original while adding your own meaning.
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 ReadError extends Error {
constructor(message: string, public readonly path: string, options?: { cause?: unknown }) {
super(message, options);
this.name = 'ReadError';
}
}
const STORE = new Map<string, string>([
['fleet.json', '[{"plate":"LAG-441-XA","seatsLeft":9}]'],
['broken.json', '{ not valid json'],
]);
// Level 1: the raw read. Knows nothing about meaning.
function rawRead(path: string): string {
const text = STORE.get(path);
if (text === undefined) throw new ReadError('not found', path);
return text;
}
// Level 2: parsing. Adds context, then passes the fault upward.
interface Bus { plate: string; seatsLeft: number }
function loadFleet(path: string): Bus[] {
const text = rawRead(path); // a not-found error travels through
try {
return JSON.parse(text) as Bus[];
} catch (err) {
// Wrap: keep the original, add what we were trying to do.
throw new ReadError('file is not valid JSON', path, { cause: err });
}
}
// Level 3: the boundary. The only level that decides what a human sees.
function summarise(path: string): string {
try {
const fleet = loadFleet(path);
const seats = fleet.reduce((n, b) => n + b.seatsLeft, 0);
return `${fleet.length} bus(es), ${seats} seats free`;
} catch (err) {
if (err instanceof ReadError) {
const because = err.cause instanceof Error ? ` [${err.cause.name}]` : '';
return `could not read ${err.path}: ${err.message}${because}`;
}
throw err;
}
}
console.log(summarise('fleet.json'));
console.log(summarise('broken.json'));
console.log(summarise('absent.json'));
test('the good path', summarise('fleet.json'), '1 bus(es), 9 seats free');
test('a parse fault is explained', summarise('broken.json').startsWith('could not read broken.json: file is not valid JSON'), true);
test('and it kept the underlying SyntaxError', summarise('broken.json').includes('SyntaxError'), true);
test('a missing file travelled up untouched', summarise('absent.json'), 'could not read absent.json: not found');
Output
The shape to take away: low levels add context, the boundary decides. rawRead throws and does not apologise. loadFleet catches only the parse fault, wraps it with what it was doing, and lets the not-found error pass straight through. Only summarise turns anything into a sentence for a human. Try-catch at every level would just produce the same message three times.