Treating Errors as Data

Let’s learn how to use errors as data to assist us in handling failure.

Common errors

Functional programs are simpler when we can use pipelines to simplify code. Transforming data is one of the fundamental tenets of Elixir. However, specific problems can arise.

Exceptions

Functions that fail often raise exceptions. When we don’t handle errors, they transition to code execution in the form of exceptions. Exceptions don’t compose neatly, and the resulting error codes aren’t always informative.

Losing context

There’s another problem with relying on pipes that fail midstream—we can often lose context. Here’s how we can go about correcting this:

  • If we can treat errors as data, managing flows in pipelines gets a little bit simpler.

  • With error data structures, later functions in a pipeline can decide how to handle them. We can report partial success or even halt on an error with context, just as the Plug framework from Phoenix does.

Get hands-on with 1400+ tech skills courses.