Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Result type for error handling in JavaScript

107 a Result type, so failure is a value

hard

Write a Result class with static ok and err constructors, map, mapErr, andThen, unwrapOr and match. Chain a validation so the first failure short-circuits the rest, and give it a toJSON so the assertions can see inside a class with private fields.

Stuck? Three hints, smallest first
  1. 1. Keep the state in private fields and never expose them. The only ways out should be unwrapOr and match, which force the caller to consider failure.
  2. 2. map takes a plain value to a plain value; andThen takes a value to another Result. Using map where you needed andThen gives you a Result inside a Result.
  3. 3. On the failure path, both map and andThen can return this unchanged. That is what makes the chain short-circuit.

The answer

class Result {
  #ok;
  #value;
  #error;

  constructor(ok, value, error) {
    this.#ok = ok;
    this.#value = value;
    this.#error = error;
  }

  static ok(value) { return new Result(true, value, undefined); }
  static err(error) { return new Result(false, undefined, error); }

  get isOk() { return this.#ok; }

  map(fn) { return this.#ok ? Result.ok(fn(this.#value)) : this; }
  mapErr(fn) { return this.#ok ? this : Result.err(fn(this.#error)); }
  andThen(fn) { return this.#ok ? fn(this.#value) : this; }
  unwrapOr(fallback) { return this.#ok ? this.#value : fallback; }
  match(handlers) { return this.#ok ? handlers.ok(this.#value) : handlers.err(this.#error); }

  toJSON() { return this.#ok ? { ok: true, value: this.#value } : { ok: false, error: this.#error }; }
}

const parseAmount = (text) => {
  const n = Number(text);
  if (text.trim() === '' || Number.isNaN(n)) return Result.err(`not a number: ${text}`);
  if (n <= 0) return Result.err('amount must be positive');
  return Result.ok(n);
};
const withinLimit = (n) => (n <= 50000 ? Result.ok(n) : Result.err('above the single-transfer limit'));

let conversions = 0;
const toKobo = (n) => {
  conversions++;
  return n * 100;
};

const good = parseAmount('4500').andThen(withinLimit).map(toKobo);
const tooBig = parseAmount('90000').andThen(withinLimit).map(toKobo);
const notANumber = parseAmount('abeg').andThen(withinLimit).map(toKobo);
const negative = parseAmount('-5');
const conversionsRun = conversions;

const failed = parseAmount('abeg');
const mapWasSkipped = failed.map(toKobo) === failed;
const shouted = failed.mapErr((e) => e.toUpperCase());
const untouched = good.mapErr((e) => e.toUpperCase()) === good;

const fallbacks = [good.unwrapOr(0), notANumber.unwrapOr(0)];
const messages = [good, tooBig].map((r) => r.match({ ok: (n) => `transfer ${n} kobo`, err: (e) => `declined: ${e}` }));

class Bare {
  #hidden = 'nothing to see';
}
const bareShape = JSON.stringify(new Bare());

console.log('good    :', JSON.stringify(good), '| too big:', JSON.stringify(tooBig));
console.log('skipped :', conversionsRun, 'conversions for four chains');
console.log('messages:', messages);
console.log('bare    :', bareShape);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('an ok carries its value, and toJSON is what makes it comparable', good, { ok: true, value: 450000 });
test('a failure carries a reason instead, and the rules are checked in the order written', [notANumber, negative], [{ ok: false, error: 'not a number: abeg' }, { ok: false, error: 'amount must be positive' }]);
test('andThen chains a function that returns a Result, without nesting one inside another', tooBig, { ok: false, error: 'above the single-transfer limit' });
test('the first failure short-circuits, so the conversion ran once across four chains', conversionsRun, 1);
test('map on a failure returns the very same instance, untouched', [mapWasSkipped, failed.isOk], [true, false]);
test('mapErr is the mirror image: it rewrites the reason and leaves an ok alone', [shouted, untouched], [{ ok: false, error: 'NOT A NUMBER: ABEG' }, true]);
test('unwrapOr is the escape hatch that cannot forget the failure case', fallbacks, [450000, 0]);
test('match makes you write both branches, which is the whole point', messages, ['transfer 450000 kobo', 'declined: above the single-transfer limit']);
test('without toJSON a class with private fields stringifies to nothing at all', bareShape, '{}');

A Result turns failure into a value, which means the type system of your head — or an actual type system — can see it. A function returning Result announces that it can fail; a function that throws does not, and every caller has to know or find out the hard way. The trade is that Result only helps for expected failures. A bug should still throw: you do not want to write andThen chains for out-of-memory.

map versus andThen is the distinction worth getting right, and it is the same one as Array#map versus Array#flatMap. map lifts a plain function into the wrapper; andThen takes a function that returns its own wrapper and does not double it up. Use map where you needed andThen and you get a Result whose value is a Result, which type-checks nowhere and fails at the match.

Two implementation notes. Returning this on the failure path is what short-circuits the chain, and the assertion counting conversions is the proof: four chains, three of them failing, one call to toKobo. And the last assertion is about the harness — JSON.stringify cannot see private fields, so a class instance stringifies to {} and every assertion about it would trivially pass. Adding toJSON gives the class a deliberate public projection, which makes it both loggable and testable.

Newsletter

New writing, when it lands.

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