javascript / expert
Snippet
The Result Monad for Error Propagation
The Result pattern replaces throwing exceptions with a returned object representing either success or failure. This functional approach makes error handling explicit in the type system, forcing developers to acknowledge potential failures and making the control flow easier to trace.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Success = (value) => ({ ok: true, value });const Failure = (error) => ({ ok: false, error });const safeJSON = (str) => {try { return Success(JSON.parse(str)); }catch (e) { return Failure(e.message); }};const res = safeJSON('{"key": "val"}');if (res.ok) {console.log(res.value.key);} else {console.error(res.error);}
Breakdown
1
return Success(JSON.parse(str))
Wraps a successful computation result in a standard container object.
2
if (res.ok) { ... }
Forces explicit checking of the operation's outcome before accessing data.