Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajeevprasanna/aa6b3982eeebd5a34f252247465e2696 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/aa6b3982eeebd5a34f252247465e2696 to your computer and use it in GitHub Desktop.
MonadError example
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