Error Handling Using EitherT

Table of contents
Reading Time: 3 minutes

Are you aware of Either, if yes then you must know how it’s use for error handling , but don’t you think things get messy when it is placed into effectful types such as Option or Future, a large amount of boilerplate is required to handle errors.

Now let’s see this code that uses Either

Now what if parseDouble and divide are rewritten to be asynchronous and return Future[Either[String, Double]] instead. The for-comprehension can no longer be used since divisionProgram now compose of Future and Either together.

Now our code looks like this

This code is messy and has less readable, and more over has error handling logic included within the program.

Now let’s see how EitherT can be used to overcome the above issues

EitherT[F[_], A, B] is a lightweight wrapper for F[Either[A, B]] that makes it easy to compose Eithers and Fs together.
F[Either[A, B]] can be converted into EitherT using the EitherT constructor as seen in our code above and we can use value method of EitherT to get F[Either[A ,B]] from EitherT[F[_], A, B].

Note:  That when F is a monad, then EitherT will also form a monad, allowing monadic combinators such as flatMap to be used in composing EitherT values.

Lets explore more of EitherT

To obtain a left version or a right version of EitherT when given an A or a B, use EitherT.leftT and EitherT.rightT respectively.

Similary, use EitherT.left and EitherT.right to convert an F[A] or an F[B] into an EitherT.

We can use EitherT.fromEither to ransform an Either to EitherT.

We also have methods to transform an Option into EitherT.

Here the first parameter is the Option itself whereas second parameter is the value to be used in case Option is None.
Similarly, we can transform F[Option] to EitherT as shown below.

I personally believe that these various methods that EitherT provides can make your life easy while writing code that involves Either with any other effectful types.
Once you start using it, you’ll also agree with me if not now.

Don’t think that EitherT is limited in above methods, there are still many things to explore.
Hopefully, this blog have open your gateway to EitherT and have leave you to explore more.



1 thought on “Error Handling Using EitherT4 min read

Comments are closed.