JavaScriptFundamental (ES6), part 1
Result type for error handling in JavaScript
107 a Result type, so failure is a value
hardWrite 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. Keep the state in private fields and never expose them. The only ways out should be
unwrapOrandmatch, which force the caller to consider failure. - 2.
maptakes a plain value to a plain value;andThentakes a value to anotherResult. Usingmapwhere you neededandThengives you a Result inside a Result. - 3. On the failure path, both
mapandandThencan returnthisunchanged. That is what makes the chain short-circuit.
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.
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.