-
-
Save rajeevprasanna/aa6b3982eeebd5a34f252247465e2696 to your computer and use it in GitHub Desktop.
MonadError example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats.MonadError | |
import cats.instances.either._ | |
import cats.instances.future._ | |
import cats.instances.try_._ | |
import cats.syntax.applicativeError._ | |
import cats.syntax.flatMap._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import scala.concurrent.{Await, Future} | |
import scala.util.Try | |
object MonadErrorExample { | |
type ThrowableEither[A] = Either[Throwable, A] | |
type ThrowableMonadError[F[_]] = MonadError[F, Throwable] | |
def safe[F[_] : ThrowableMonadError](): F[Int] = { | |
val errorHandler = implicitly[ThrowableMonadError[F]] | |
errorHandler.catchNonFatal { | |
5 / 0 | |
}.recoverWith { | |
case ex => errorHandler.catchNonFatal { | |
15 / 0 | |
} | |
}.flatMap { result: Int => | |
errorHandler.pure(10) | |
}.recover { | |
case ex => 1 | |
} | |
} | |
safe[Try]() | |
Await.result(safe[Future](), 10 seconds) | |
safe[ThrowableEither]() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment