MonadError

MonadError is the typeclass used to explicitly represent errors during sequential execution. It is parametrized to an error type E, which means the datatype has at least a “success” and a “failure” version. These errors can come in the form of Throwable, Exception, or any other type hierarchy of the user’s choice.

MonadError extends from ApplicativeError, which is already used to represent errors in independent computations. This way, all the methods ApplicativeError provides to handle recovery from errors are also available in MonadError.

Main Combinators

MonadError inherits all the combinators available in ApplicativeError and Monad. It also adds one of its own.

raiseError

Inherited from ApplicativeError. A constructor function. It lifts an exception into the computational context of a type constructor.

import arrow.*
import arrow.core.*
import arrow.core.extensions.either.applicativeError.*

val eitherResult: Either<String, Int> =
  "BOOM!".raiseError()

eitherResult
// Either.Left(BOOM!)

Kind<F, A>.ensure

Tests a predicate against the object, and, if it fails, it executes a function to create an error.

import arrow.core.extensions.either.monadError.*

Either.Right(1).ensure({ RuntimeException("Failed predicate") }, { it > 0 })
// Either.Right(1)
Either.Right(1).ensure({ RuntimeException("Failed predicate") }, { it < 0 })
// Either.Left(java.lang.RuntimeException: Failed predicate)

Comprehensions

fx.monadThrow

It starts a Monad Comprehension that wraps any exception thrown in the block inside raiseError().

Laws

Arrow provides MonadErrorLaws in the form of test cases for internal verification of lawful instances and third party apps creating their own MonadError instances.

Do you like Arrow?

Arrow Org
<