Skip to content

Instantly share code, notes, and snippets.

@jackcviers
Created March 27, 2017 21:59
Show Gist options
  • Save jackcviers/804b6d8d1b2ead210367a104a746fd00 to your computer and use it in GitHub Desktop.
Save jackcviers/804b6d8d1b2ead210367a104a746fd00 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