Created
February 13, 2021 12:18
-
-
Save sshark/f5e0d213fcce0b4463cfdd2d8dcda3ea to your computer and use it in GitHub Desktop.
How to display the exact error at each stage
This file contains hidden or 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
| package org.teckhooi | |
| import cats.effect.{ExitCode, IO, IOApp} | |
| import cats.implicits.catsSyntaxEitherId | |
| import scala.util.Try | |
| object EitherErrorHandlingInIO extends IOApp { | |
| override def run(args: List[String]): IO[ExitCode] = { | |
| (for { | |
| x <- IO | |
| .fromEither( | |
| get(11).fold(new Exception("Number out of range").asLeft[Int])(x => x.asRight[Exception])) | |
| .attempt | |
| y <- IO.fromEither(x.flatMap(xx => Try(div(xx)).toEither)).attempt | |
| _ <- y.fold(t => IO(println(s"## ${t.getMessage}")), r => IO(println(r))) | |
| } yield ()).as(ExitCode.Success) | |
| } | |
| def get(i: Int): Option[Int] = if (i > -5 && i < 10) Some(i) else None | |
| def div(i: Int): Double = 42 / i | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment