In the last section, we looked at how to add error handling to a parser that we built using State , but as you’ve seen throughout this book the problem of dealing with error handling in some sort of computation is common. Another example where you’ve already had first-hand experience with this is in handling failures inside of IO actions. We’ve previously handled errors inside of IO actions by raising exceptions using ioError . Although we’ve managed to get by with IO exceptions, they have a couple of problems. First, we’re risking errors caused by unhandled exceptions. We can certainly argue that developers should be responsible and handle exceptions appropriately but there’s nothing to force us to catch them, and so we’re risking bugs. Second, using IO exceptions for errors in our application logic can confuse different sorts of errors that should be handled in different ways.

Let’s see if we can add error handling to an IO action using the same approach we used with our parser. We’ll start by creating a new type called EitherIO :

​  ​ newtype ​ ​ EitherIO ​ a = ​ EitherIO ​
​  {runIO :: ​ IO ​ (​ Either ​ ​ String ​ a)}

Next we’ll need to define Functor , Applicative , and Monad instances for EitherIO :

​  ​ instance ​ ​ Functor ​ ​ EitherIO ​ ​ where ​
​  fmap f exceptionalIO =
​  ​ EitherIO ​ $ (fmap . fmap) f (runIO exceptionalIO)
​  
​  ​ instance ​ ​ Applicative ​ ​ EitherIO ​ ​ where ​
​  pure a = ​ EitherIO ​ $ (pure . pure) a
​  f <*> a = ​ EitherIO ​ $ ​ do ​
​  f' <- runIO f
​  a' <- runIO a
​  pure $ f' <*> a'
​  
​  ​ instance ​ ​ Monad ​ ​ EitherIO ​ ​ where ​
​  return = pure
​  a >>= f = ​ EitherIO ​ $ ​ do ​
​  val <- runIO a
​  ​ case ​ val ​ of ​
​  ​ Left ​ err -> pure (​ Left ​ err)
​  ​ Right ​ val' -> runIO $ f val'

Looking at this example, you may notice something interesting: all of these type class instances are identical to the instances we defined for Parser . You can carefully read the examples line by line, or try copying the implementation you created for Parser and change the name of the type. That’s because we’re not relying on any implementation details of the computation we’re embedding our error handling in. It also means that our approach to embedding error handling won’t just work for State and IO , it’ll work for any type that has a Monad instance.

As you can imagine, it would be tedious to copy and paste the same instance definitions every time we want to add error handling to some type. Thankfully, we don’t have to. Instead of creating a new type and defining a new way to embed errors every time, we can create a more general type that lets us transform a plain type into a type that can fail. Types like this that let us transform one type of Monad into another with more capabilities are known as monad transformers . Throughout this chapter, you’ll learn about several different monad transformers, but for now we’ll limit ourselves to handling.

Exceptional Transformers

Let’s start looking at how we can build a more general approach to error handling by creating a new module. Both the mtl and transformers libraries refer to the monad transformer we’re building as ExceptT . We’ll stick with that name for both the name of our module, and the name of the general error handling transformer that we’re going to define:

​  ​ {-# LANGUAGE KindSignatures #-} ​
​  ​ module ​ ​ ExceptT ​ ​ where ​
​  ​ import ​ ​ Control.Applicative ​
​  ​ import ​ ​ Data.Kind ​ (​ Type ​)

The definition of ExceptT is similar to the definitions of Parser and EitherIO , but instead of assuming we’ll always use a String for error handling and a State or IO action for the underlying monad, we’ll make those additional parameters to ExceptT :

​  ​ newtype ​ ​ ExceptT ​ (e :: ​ Type ​) (m :: ​ Type ​ -> ​ Type ​) (a :: ​ Type ​) = ​ ExceptT ​
​  { runExceptT :: m (​ Either ​ e a) }

In this example, we’re using KindSignatures to help make it clear that one of the type parameters that we’ve added, m , is a higher kinded type . When you first learned about higher kinded types we only looked at them when we were dealing with type classes and function types, but as you can see from the example, higher kinded types are also useful as type parameters. In the case of ExceptT , the higher kinded type m represents whatever monadic type we’re adding exception handling to.

As you might expect, the Functor , Applicative , and monad instances for ExceptT are similar to the instances we defined for EitherIO and Parser . One difference is that, when we were writing those instances, we could freely use functions like fmap or use do notation because the IO and State actions that we were wrapping have Functor , Applicative , and Monad instances. Now that we’re wrapping a generic m , we need to be explicit about adding constraints to our instances:

​  ​ instance ​ ​ Functor ​ m => ​ Functor ​ (​ ExceptT ​ e m) ​ where ​
​  fmap f a = ​ ExceptT ​ $ (fmap . fmap) f (runExceptT a)
​  
​  ​ instance ​ ​ Monad ​ m => ​ Applicative ​ (​ ExceptT ​ e m) ​ where ​
​  pure a = ​ ExceptT ​ $ pure (pure a)
​  f <*> a = ​ ExceptT ​ $ ​ do ​
​  f' <- runExceptT f
​  a' <- runExceptT a
​  pure $ f' <*> a'
​  
​  ​ instance ​ ​ Monad ​ m => ​ Monad ​ (​ ExceptT ​ e m) ​ where ​
​  return = pure
​  a >>= f = ​ ExceptT ​ $ ​ do ​
​  val <- runExceptT a
​  ​ case ​ val ​ of ​
​  ​ Left ​ err -> pure $ ​ Left ​ err
​  ​ Right ​ val' -> runExceptT $ f val'

Now that we’ve added our instances, we need to define the fundamental operations of ExceptT . When we defined State , we identified two basic operations we could use to define all our other stateful computations: get and put . With monad transformers, we’re instead going to define the basic operations we’re adding to some computation. In our example, we’ll add three basic operations:

  1. throwError will let us raise a new exception if we encounter an error.
  2. catchError will allow us to handle an exception that has been raised.
  3. succeed will let us take a computation that can’t fail and embed it inside of an ExceptT computation.

Try writing an implementation of these functions yourself. You should be able to write them using what you’ve already learned in this chapter. Once you’ve tried writing them yourself, take a look at the example and see how your versions compare:

​  throwError :: ​ Monad ​ m => e -> ​ ExceptT ​ e m a
​  throwError exception = ​ ExceptT ​ (pure $ ​ Left ​ exception)
​  
​  catchError :: ​ Monad ​ m => (e -> ​ ExceptT ​ e m a) -> ​ ExceptT ​ e m a -> ​ ExceptT ​ e m a
​  catchError handler action = ​ ExceptT ​ $ ​ do ​
​  result <- runExceptT action
​  ​ case ​ result ​ of ​
​  ​ Left ​ err -> runExceptT (handler err)
​  ​ Right ​ val -> pure (​ Right ​ val)
​  
​  succeed :: ​ Monad ​ m => m a -> ​ ExceptT ​ e m a
​  succeed a = ​ ExceptT ​ (​ Right ​ <$> a)

Now that we’ve implemented ExceptT and defined some basic operations for working with exceptions, let’s revisit a couple of our earlier examples and take a look at how we can reimplement them using ExceptT . We’ll start by re-visiting Parser , and then look at some examples of using ExceptT to add error handling to IO actions.

Parsing with ExceptT

We’ll start our next parsing example by creating a new module and yet another definition of Parser . This time, we’ll use a type alias:

​  ​ module ​ ​ ExceptTParser ​ ​ where ​
​  ​ import ​ ​ ExceptT ​
​  ​ import ​ ​ Control.Monad ​
​  ​ import ​ ​ Data.Char ​ (​ isDigit ​, ​ isSpace ​)
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ Text
​  ​ import ​ ​ State ​
​  
​  ​ type ​ ​ Parser ​ a = ​ ExceptT ​ ​ String ​ (​ State ​ ​ Text ​) a

Although using a type alias means that our Parser implementation is going to be transparent to our users, we can still make our parser easier to use by adding a utility function for parsing some text. This is a common pattern when building APIs that use monad transformers, since forcing users to manually run all of the nested computations has poor ergonomics.

​  runParser :: ​ Parser ​ a -> ​ Text ​ -> ​ Either ​ ​ String ​ a
​  runParser = evalState . runExceptT

The definition of the parsers won’t need to change drastically compared to our earlier examples. Let’s look at a few examples for now. You’ll finish re-implementing a complete monad transformer-based parser at the end of this chapter as an exercise.

We’ll start by looking at parseNextCharacter :

​  parseNextCharacter :: ​ Parser ​ ​ Char ​
​  parseNextCharacter = ​ do ​
​  input <- succeed get
​  when (​ Text ​.null input) $
​  throwError ​ "parseNextCharacter: unexpected end of input" ​
​  succeed . put . ​ Text ​.tail $ input
​  pure $ ​ Text ​.head input

As you can see, there are only a couple of differences between this new version and the previous one. First, we’ve replaced failParser with our new more general throwError function. The behavior is the same, but we’re now using a more general purpose function that works with any ExceptT action. Second, we’re using succeed to lift put into our exceptT action. The need to explicitly lift operations like get and put from State into our ExceptT -wrapped action is a little bit annoying. Later on in this chapter, you’ll learn how to rewrite some basic operations like get and put so that you don’t need to explicitly lift them as often, but the need to occasionally lift operations like this is one of the down sides of working with monad transformers.

Not every function implemented with ExceptT will end up looking so similar to our earlier versions. One function that we can write differently is word . Using ExceptT has simplified our how we can handle the expected dropChar failure at the end of our input. You’ll define an Alternative instance for ExceptT as an exercise at the end of this chapter to make this even easier.

​  word :: ​ Parser ​ ​ Text ​
​  word = ​ do ​
​  nextWord <- takeUntil isSpace
​  when (​ Text ​.null nextWord) $
​  throwError ​ "unexpected end of input" ​
​  
​  
​  ignoreException dropChar
​  pure nextWord
​  ​ where ​
​  ignoreException =
​  catchError (const $ pure ())

Having seen the patterns, you should be able to continue reimplementing the remainder of your ExceptT -based parser on your own.