Chapter 6. Functional error handling

 

This chapter covers

  • Representing alternative outcomes with Either
  • Chaining operations that may fail
  • Distinguishing business validation from technical errors

Error handling is an important part of our applications, and one aspect in which the functional and imperative programming styles differ starkly:

  • Imperative programming uses special statements like throw and try/catch, which disrupt the normal program flow, thus introducing side effects, as discussed in chapter 2.
  • Functional programming strives to minimize side effects, so throwing exceptions is generally avoided. Instead, if an operation can fail, it should return a representation of its outcome including an indication of success or failure, as well as its result (if successful), or some error data otherwise. In other words, errors in FP are just payload.

There are lots of problems with the imperative, exception-based approach. It has been said that throw has similar semantics to goto, and this begs the question of why imperative programmers have banished goto but not throw.[1] There’s also a lot of confusion around when to use exceptions and when to use other error-handling techniques. I feel that the functional approach brings a lot more clarity to the complex area of error handling, and I hope to convince you of this through the examples in this chapter.

6.1. A safer way to represent outcomes

6.2. Chaining operations that may fail

6.3. Validation: a perfect use case for Either

6.4. Representing outcomes to client applications

6.5. Variations on the Either theme

sitemap