diag 30301e9118ce6cc3ac419a37c38946cd
Figure 1. Common error-handling methods provided by MonadError.

MonadError is a typeclass that describes how to raise and handle errors. It is provided by the Typelevel Cats functional programming library.

The MonadError[F[_], E] typeclass has two type parameters:

F[_]

the effect type, which itself takes a type parameter; and

E

the error type.

For example, the MonadError where F is Future will have error type Throwable, i.e., MonadError[Future, Throwable], because failed Future values contain a value of type Throwable.

Methods of the MonadError typeclass are either introduction forms or combinators.

Introduction forms create a value of the effect type F. The most important introduction form provided by MonadError is raise:

def raise[A](error: E): F[A]

Combinators transform a value of the effect type into another value of the same effect type. There are a few general cases for handling an error:

perform a side-effect

onError

transform the error

adaptError
handleError, handleErrorWith
recover, recoverWith

transform the entire effect

redeem, redeemWith

expose/hide errors as values

attempt (expose)
rethrow (hide)


essential effects cover

You can learn more about effects and effectful error handling in the book Essential Effects, available at https://essentialeffects.dev.