Custom DatabaseError in TypeScript
7 A DatabaseError around a query
fairPerform a database operation and use a custom error class for database failures, logging what went wrong. Adapted: an in-memory table stands in for the database.
Stuck? Three hints, smallest first
- 1. Keep the original failure on the error as a
cause, so nothing is lost. - 2. JavaScript’s
Erroraccepts{ cause }as a second argument. - 3. Log at the boundary only. Logging in every layer produces the same error four times.
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 DatabaseError extends Error {
constructor(message: string, public readonly query: string, options?: { cause?: unknown }) {
super(message, options);
this.name = 'DatabaseError';
}
}
// The stand-in table.
const SEATS = new Map<string, string>([
['1A', 'BK-0001'],
['1B', 'BK-0001'],
]);
let connected = true;
function query(sql: string, seat: string): string | null {
if (!connected) {
// A low-level failure, wrapped so callers get one error type.
const underlying = new Error('connection refused');
throw new DatabaseError('cannot reach the database', sql, { cause: underlying });
}
if (!sql.startsWith('SELECT')) {
throw new DatabaseError(`unsupported statement: ${sql}`, sql);
}
return SEATS.get(seat) ?? null;
}
const log: string[] = [];
function whoHasSeat(seat: string): string {
try {
const reference = query('SELECT reference FROM seats WHERE seat = ?', seat);
return reference === null ? `${seat} is free` : `${seat} is held by ${reference}`;
} catch (err) {
if (err instanceof DatabaseError) {
// Log once, here at the boundary, with the cause if there was one.
const because = err.cause instanceof Error ? ` (caused by: ${err.cause.message})` : '';
log.push(`${err.name}: ${err.message}${because}`);
return `${seat}: lookup unavailable`;
}
throw err;
}
}
console.log(whoHasSeat('1A'));
console.log(whoHasSeat('3C'));
connected = false;
console.log(whoHasSeat('1A'));
connected = true;
for (const line of log) console.log('LOG', line);
test('a held seat', whoHasSeat('1A'), '1A is held by BK-0001');
test('a free seat', whoHasSeat('3C'), '3C is free');
test('one failure was logged', log.length, 1);
test('the log kept the underlying cause', log[0]?.includes('connection refused'), true);
test('the caller got a usable answer, not a crash', (() => { connected = false; const r = whoHasSeat('1B'); connected = true; return r; })(), '1B: lookup unavailable');
Output
Adapted: the usual version uses a real database. Two habits worth keeping. { cause } is standard JavaScript and lets you wrap a low-level failure in a meaningful one without throwing away the detail. And the logging happens once, at the boundary, rather than at every level, which is what stops a single fault filling your log four times.