Emmanuel Akinfulubi

TypeScriptError handling

Roll back a transaction on error in TypeScript

12 A transaction that rolls back when a step fails

hard

Interact with a database and perform a transaction, handling failures throughout so that a failed transaction is rolled back and leaves nothing behind. Adapted: an in-memory table with a snapshot stands in for the database.

Stuck? Three hints, smallest first
  1. 1. Take a copy of the state before you start, and restore it if anything throws.
  2. 2. finally is the right place for cleanup, because it runs whether or not there was a fault.
  3. 3. The test that matters is that the data is unchanged after a failure, not just that an error was thrown.

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

class TransactionError extends Error {
  constructor(message: string, public readonly rolledBack: boolean) {
    super(message);
    this.name = 'TransactionError';
  }
}

// The stand-in table: seat -> booking reference.
let seats = new Map<string, string>([['1A', 'BK-0001']]);

const audit: string[] = [];

function hold(seat: string, reference: string): void {
  const taken = seats.get(seat);
  if (taken !== undefined) throw new Error(`${seat} already held by ${taken}`);
  seats.set(seat, reference);
}

/** Run several holds as one unit: either all of them stick, or none do. */
function transaction(reference: string, wanted: string[]): string {
  const snapshot = new Map(seats);       // the rollback point
  let committed = false;

  try {
    for (const seat of wanted) hold(seat, reference);
    committed = true;
    return `${reference}: held ${wanted.join(', ')}`;
  } catch (err) {
    const because = err instanceof Error ? err.message : 'unknown';
    throw new TransactionError(`${reference} failed: ${because}`, true);
  } finally {
    // finally runs on both paths, which is exactly what cleanup needs.
    if (!committed) {
      seats = snapshot;
      audit.push(`rolled back ${reference}`);
    } else {
      audit.push(`committed ${reference}`);
    }
  }
}

console.log(transaction('BK-0002', ['2A', '2B']));
console.log('seats now:', [...seats.keys()].join(', '));

let failure = '';
try {
  // 3A is free but 1A is taken, so the whole thing must come undone.
  transaction('BK-0003', ['3A', '1A']);
} catch (err) {
  failure = err instanceof TransactionError ? err.message : '';
}

console.log('failure:', failure);
console.log('seats after the failure:', [...seats.keys()].join(', '));
for (const line of audit) console.log('AUDIT', line);

test('a good transaction commits', seats.get('2A'), 'BK-0002');
test('both seats of it stuck', seats.get('2B'), 'BK-0002');
test('the failing one reported why', failure.includes('already held by BK-0001'), true);
test('and it rolled back the seat it had already taken', seats.has('3A'), false);
test('the table is exactly as it was', [...seats.keys()].sort(), ['1A', '2A', '2B']);
test('the audit recorded both outcomes', audit, ['committed BK-0002', 'rolled back BK-0003']);

Output


      

Adapted: the usual version uses a real database and its transaction support. The important assertion is the fourth: 3A was successfully held before 1A failed, and after the rollback it is free again. A half-applied transaction is worse than a rejected one, and finally is what guarantees the cleanup runs whichever way the function exits.

Newsletter

New writing, when it lands.

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