MonadError
.digraph MonadError { rankdir=LR node [fontname=courier shape=none] edge [fontname=courier color=grey] fa [label=<<b>F[<font color="green3">A</font>]</b>>] e [label=<<font color="red3">E</font>>] fa2 [label=<F[<font color="green3">A</font>]>] fb [label=<F[<font color="blue3">B</font>]>] fea [label=<F[Either[<font color="red3">E</font>, <font color="green3">A</font>]]>] e -> fa [label=<raise>] fa -> fa2 [label=< handleError(f: <font color="red3">E</font> ⇒ <font color="green3">A</font>) <br align="left"/> handleErrorWith(f: <font color="red3">E</font> ⇒ F[<font color="green3">A</font>]) <br align="left"/> recover(f: PartialFunction[<font color="red3">E</font>, <font color="green3">A</font>]) <br align="left"/> recoverWith(f: PartialFunction[<font color="red3">E</font>, F[<font color="green3">A</font>]]) <br align="left"/> onError(f: PartialFunction[<font color="red3">E</font>, F[Unit]]) <br align="left"/> adaptError(f: <font color="red3">E</font> ⇒ <font color="red3">E</font>) <br align="left"/> >] fa:sw -> fea:nw [xlabel="attempt"] fea:ne -> fa:se [label="rethrow"] { rank=same; fa, fea, e} fa -> fb [label=< redeem(recover: <font color="red3">E</font> ⇒ <font color="blue3">B</font>, f: <font color="green3">A</font> ⇒ <font color="blue3">B</font>) <br align="left"/> redeemWith(recover: <font color="red3">E</font> ⇒ F[<font color="blue3">B</font>], f: <font color="green3">A</font> ⇒ F[<font color="blue3">B</font>]) <br align="left"/> >] }
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 |
|
transform the error |
|
transform the entire effect |
|
expose/hide errors as values |
|
You can learn more about effects and effectful error handling in the book Essential Effects, available at https://essentialeffects.dev.