Elegant Error Handling with the JavaScript “Either” Monad
Several comments here are along the lines of &quot;I haven&#x27;t done much monadic error handling but here&#x27;s why it&#x27;s bad.&quot;<p>That&#x27;s silly because the benefits of this type of programming can&#x27;t be grokked until you use it on real projects.. it&#x27;s honest-to-goodness not enough to look at small examples and judge whether it&#x27;s worthwhile or not.<p>There&#x27;s a lot of this realization going around actually - for example Rust&#x27;s main raison d&#x27;être is basically: &quot;look - we _can_ write safe c&#x2F;c++, some of us can even nail it perfect every time in small examples, but in large apps it&#x27;s inevitable that we&#x27;ll all make mistakes&quot;<p>Here&#x27;s two issues with try&#x2F;catch in real-world apps:<p>1. You aren&#x27;t forced to write it. It&#x27;s simply possible to forget that a function might fail (e.g. when that failure is defined as a side-effect). This is even worse when there&#x27;s no type system forcing you to think about it. We all make this mistake!<p>2. You can&#x27;t easily distinguish between expected errors and unexpected errors - and even where you can, dealing with that becomes a big mess.<p>Unexpected errors (like &quot;out of memory&quot;, &quot;computer is quitting&quot;, &quot;electricity is gone&quot;) - _should_ crash and burn and stop the app (unless you explicitly have a way to recover from it - in which case it&#x27;s actually an _expected_ error). Letting the app continue on where there&#x27;s undefined behavior is dangerous.<p>Expected errors (like &quot;user not found&quot;, &quot;wrong password&quot;, perhaps even &quot;network down&quot;) need to be dealt with. Every single time. Even in a function where it might not happen 99.999% of the time - that one rare time where it happens is especially hard to duplicate and fix.<p>That said, I agree with the comments that say it&#x27;s a bit awkward in JS, and much less effective without a type system forcing the right constraints. I like using FP-TS[0] with typescript for extra help at &quot;transpile&quot; time, but Sanctuary[1] (based on FantasyLand[2]) with the runtime checking turned on is pretty incredible too.<p>With _some_ type system making sure that we&#x27;re following the rules, monadic error handling is definitely more elegant and safer than try&#x2F;catch.<p>[0] <a href="https:&#x2F;&#x2F;gcanti.github.io&#x2F;fp-ts&#x2F;modules&#x2F;" rel="nofollow">https:&#x2F;&#x2F;gcanti.github.io&#x2F;fp-ts&#x2F;modules&#x2F;</a>
[1] <a href="https:&#x2F;&#x2F;sanctuary.js.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;sanctuary.js.org&#x2F;</a>
[2] <a href="https:&#x2F;&#x2F;github.com&#x2F;fantasyland&#x2F;fantasy-land" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;fantasyland&#x2F;fantasy-land</a>