Emmanuel Akinfulubi

TypeScriptError handling

Custom error types per workflow step in TypeScript

11 A workflow where each step has its own error type

hard

Simulate a workflow of several steps. Give each step its own error class, pass failures up, and log which step failed.

Stuck? Three hints, smallest first
  1. 1. A shared base class lets a caller catch the whole family with one instanceof.
  2. 2. Put the step name on the base class so logging is uniform.
  3. 3. Run the same workflow with different inputs so each step fails at least once.

The answer, and proof it works

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)}`)
  );
}

// A shared base, so one instanceof catches the whole family.
abstract class WorkflowError extends Error {
  constructor(message: string, public readonly step: string) {
    super(message);
    this.name = new.target.name;      // each subclass gets its own name free
  }
}

class ValidateError extends WorkflowError {
  constructor(message: string) { super(message, 'validate'); }
}
class ReserveError extends WorkflowError {
  constructor(message: string) { super(message, 'reserve'); }
}
class PayError extends WorkflowError {
  constructor(message: string) { super(message, 'pay'); }
}

interface Request { seats: number; card: string }

const AVAILABLE = 3;

function validate(req: Request): Request {
  if (req.seats < 1) throw new ValidateError('at least one seat is required');
  return req;
}

function reserve(req: Request): number {
  if (req.seats > AVAILABLE) throw new ReserveError(`only ${AVAILABLE} seats left`);
  return req.seats;
}

function pay(req: Request, seats: number): string {
  if (!req.card.startsWith('4')) throw new PayError('card was declined');
  return `paid for ${seats} seat(s)`;
}

const log: string[] = [];

function runWorkflow(req: Request): string {
  try {
    const valid = validate(req);
    const seats = reserve(valid);
    return pay(valid, seats);
  } catch (err) {
    if (err instanceof WorkflowError) {
      // One handler covers all three, because they share a base.
      log.push(`failed at "${err.step}" (${err.name}): ${err.message}`);
      return `could not complete: ${err.message}`;
    }
    throw err;
  }
}

console.log(runWorkflow({ seats: 2, card: '4111' }));
console.log(runWorkflow({ seats: 0, card: '4111' }));
console.log(runWorkflow({ seats: 9, card: '4111' }));
console.log(runWorkflow({ seats: 2, card: '9999' }));

for (const line of log) console.log('LOG', line);

test('the happy path', runWorkflow({ seats: 2, card: '4111' }), 'paid for 2 seat(s)');
test('validate failed', log[0]?.includes('failed at "validate"'), true);
test('reserve failed', log[1]?.includes('failed at "reserve"'), true);
test('pay failed', log[2]?.includes('failed at "pay"'), true);
test('each subclass reported its own name', log[2]?.includes('PayError'), true);
test('three failures logged', log.length, 3);

Output


      

this.name = new.target.name is the trick worth stealing. new.target is the class new was actually called on, so each subclass gets the right name in its logs without repeating a line in every constructor. The shared WorkflowError base means the caller writes one instanceof instead of three.

Newsletter

New writing, when it lands.

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