JavaScriptFundamental (ES6), part 2
Ok and Err result types instead of exceptions in JavaScript
38 A Result type instead of exceptions
hardBuild Ok and Err with map, mapErr, andThen and unwrapOr, plus attempt(fn) that turns a throwing function into a value. Prove the mapper is never called on the failure path, and that a rejected promise becomes data rather than an exception.
Stuck? Three hints, smallest first
- 1. Two constructors, same method names, opposite behaviour. That is the entire pattern.
- 2.
mapon anErrreturns theErruntouched and never calls your function. - 3.
andThenis for a step that can itself fail, so it returns a Result rather than a value.
const Ok = (value) => ({
ok: true,
value,
map: (fn) => Ok(fn(value)),
mapErr: () => Ok(value),
andThen: (fn) => fn(value),
unwrapOr: () => value,
});
const Err = (error) => ({
ok: false,
error,
map: () => Err(error), // your function is never called
mapErr: (fn) => Err(fn(error)),
andThen: () => Err(error),
unwrapOr: (fallback) => fallback,
});
const attempt = (fn) => { try { return Ok(fn()); } catch (err) { return Err(err.message); } };
const attemptAsync = (promise) => promise.then(Ok, (err) => Err(err.message));
// The methods make these objects awkward to compare, so project them first.
const shape = (result) => (result.ok ? ['ok', result.value] : ['err', result.error]);
let mapperCalls = 0;
const doubled = Ok(1500).map((amount) => { mapperCalls++; return amount * 2; });
const skipped = Err('till offline').map((amount) => { mapperCalls++; return amount * 2; });
const parsed = attempt(() => JSON.parse('{"till":"yaba"}'));
const broken = attempt(() => JSON.parse('{till:'));
const chained = Ok(3).andThen((n) => (n > 0 ? Ok(n * 100) : Err('not a positive count')));
const shortCircuit = Err('nothing to work with').andThen(() => Ok('never reached'));
const defaults = [Ok(10).unwrapOr(0), Err('boom').unwrapOr(0)];
const fromRejection = shape(await attemptAsync(Promise.reject(new Error('gateway down'))));
const tidied = shape(Err('ECONNRESET').mapErr((message) => 'network: ' + message));
console.log('success :', shape(doubled), '- mapper calls:', mapperCalls);
console.log('failure :', shape(skipped));
console.log('parse failure as data:', [broken.ok, broken.error.length > 0]);
console.log('from a rejection :', fromRejection);
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('map transforms the success', shape(doubled), ['ok', 3000]);
test('and is simply not called on a failure', [shape(skipped), mapperCalls], [['err', 'till offline'], 1]);
test('attempt turns a throw into a value you can pass around', [parsed.ok, parsed.value.till], [true, 'yaba']);
test('so a parse failure stops being an exception', [broken.ok, typeof broken.error], [false, 'string']);
test('andThen chains a step that can itself fail', shape(chained), ['ok', 300]);
test('and short-circuits the moment something has failed', shape(shortCircuit), ['err', 'nothing to work with']);
test('unwrapOr is the one place a default appears', defaults, [10, 0]);
test('a rejected promise becomes an Err, so nothing throws', fromRejection, ['err', 'gateway down']);
test('mapErr rewrites the failure and leaves the success path alone', tidied, ['err', 'network: ECONNRESET']);
The point of a Result is that failure is in the type, so it cannot be forgotten. An exception is invisible in a function's signature: nothing tells a caller that JSON.parse throws, and the reminder arrives in production. A function returning Ok | Err forces the question at the call site, because there is no value to use until you have said what happens if there is none.
The second assertion is the whole mechanism in one line. Err.map ignores its argument, so a five-step pipeline over a failed Result runs none of the five and the original error falls out of the end unchanged. That is the same short-circuit a throw gives you, achieved without unwinding the stack — and unlike a throw, it does not skip past the caller who was meant to handle it.
Where this earns its keep: expected failures. A form field that will not parse, a lookup that may miss, a payment the bank declines — none of those are exceptional, and modelling them as exceptions means try/catch as ordinary control flow. Keep throw for the genuinely unexpected, where you want the stack unwound to a boundary that logs and gives up.
The cost is honest: two representations of failure in one codebase, and a conversion at every edge. attempt is that edge going in; unwrapOr, or a final if (!result.ok) throw, is the edge going out. Pick the boundary deliberately rather than letting both styles diffuse through every layer.