A monad transformer for exception handling.
A monad transformer for exception handling.
As a monad transformer, TryT
should be used with another monadic data type, like scala.Function0.
import cats.instances.function._ import scala.util._ import com.thoughtworks.zerocost.tryt._ type TryName[+A] = TryT[Function0, A]
Given a validate
function,
def validate(s: String): Int = s.toInt
when creating a TryT
-transformed scala.Function0 from the validate
,
import cats.syntax.all._ val invalidTry: TryName[Int] = TryT(() => Try(validate("invalid input")))
then the exceptions thrown in validate
call should be converted to a scala.util.Failure;
val TryT(failure) = invalidTry
failure() should be(an[Failure[_]])
and when there is no exception thrown in validate
call,
val validTry: TryName[Int] = validate("42").pure[TryName]
then the result of validate
call should be converted to a scala.util.Success;
val TryT(success) = validTry success() should be(Success(42))
and when the TryT
-transformed scala.Function0 is built from a for
-comprehension,
val invalidForComprehension: TryName[Int] = validate("42").pure[TryName].flatMap { i => validate("invalid input").pure[TryName].map { j => i + j } }
then the exceptions thrown in the for
-comprehension should be converted to a scala.util.Failure;
val TryT(failure2) = invalidTry
failure2() should be(an[Failure[_]])
This TryT
type is an opacity alias to F[Try[A]]
.
All type classes and helper functions for this TryT
type are defined in the companion object TryT
This TryT
transfomer is similar to cats.data.EitherT,
except TryT
handles exceptions thrown in callback functions passed to
map, flatMap or pure.
The namespace that contains the covariant TryT.