Handling Impure Functions with the Error Monad

Learn how to use error monads for exception handling in Elixir.

Introduction to error monads

The error monad is a data structure that helps us combine functions that can result in an error. It allows us to put functions into a clear sequence, handling the error at a unique point reducing conditional codes when functions can have unexpected results. We should use it in our codebase when there are many functions in sequence, and some of them can fail. For example, maybe we have five functions that must be executed in sequence, but some of them are prone to failure.

You may have heard of monads—they are famous in languages with strong and static typing, such as Haskell. Monads have a strong mathematical theory and concepts like functors, applicatives, and monoids. But don’t worry, we’ll only focus on how to use monads in practice.

In general, a monad wraps a value with properties that give more information about that value—they provide the context. Having a value with context makes possible the process of combining functions with values to make automatic decisions. For example, if we have context for when a value is an error or a success, we can automatically skip function executions when the value is an error. Take a look at this example:

Get hands-on with 1200+ tech skills courses.