Skip to content

Instantly share code, notes, and snippets.

@sshark
Created February 13, 2021 12:18
Show Gist options
  • Select an option

  • Save sshark/f5e0d213fcce0b4463cfdd2d8dcda3ea to your computer and use it in GitHub Desktop.

Select an option

Save sshark/f5e0d213fcce0b4463cfdd2d8dcda3ea to your computer and use it in GitHub Desktop.
How to display the exact error at each stage
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