6 Error Handling

 

In this chapter you will learn how to

  • handle all errors without nulls and exceptions
  • make sure all corner cases are handled
  • indicate all the possible errors in the function signature
  • compose bigger functionalities from smaller functions in the presence of different possible errors
  • return user-friendly and descriptive errors

There are two ways to write error-free programs; only the third one works.

— Alan Perlis, "Epigrams on Programming"

6.1 Handling lots of different errors, gracefully

We can’t write code that never fails. That’s why we need to embrace all possible errors and make sure our code can handle them and recover from them gracefully. In this chapter we will discover how helpful it is to think about errors in terms of immutable values returned from pure functions. As always, we will learn based on a real-world example:

TV show parsing engine

In this chapter we’ll be dealing with popular TV shows. We’ll start with simple requirements and then add more of them to make a full-blown TV show parsing engine. There will be lots of corner cases to handle. We’ll use them to learn how to use FP techniques to make sure all of them are covered gracefully, without polluting the codebase.

TV

6.2      Is it even possible to handle them all?

6.3      Sort the list of TV shows by their running time

6.4      Implementing the sorting requirement

6.5      Dealing with data coming from the outside world

6.6      Functional design: building from small blocks

6.7      Parsing Strings into immutable objects

6.8      Parsing a List is just parsing one element

6.9      Parsing a String into a TvShow

6.10  What about potential errors?

6.11  Is returning null a good idea?

6.12  How to handle potential errors more gracefully?

6.13  Implementing a function that returns an Option

6.14  Option forces us to handle possible errors

6.15  Building from small blocks

6.16  Functional design is building from small blocks

6.17  Writing a small safe function that returns an Option

6.18  Functions, values and expressions

6.19  Practicing safe functions that return Options

6.20  How do errors propagate?

6.21  Values represent errors

6.22  Option, for comprehension and checked exceptions...

6.23  What about checked exceptions?

6.24  Conditional recovery