Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Error handling and logging
import cats._
import cats.data._
import cats.implicits._
object EitherTLogging {
def divide[F[_]](dividend: Int, divisor: Int)(implicit F: ApplicativeError[F, String]): F[Int] = {
if (divisor === 0) F.raiseError("division by zero")
else F.pure(dividend / divisor)
}
type ErrorOr[A] = Either[String, A]
def logDivide(a: Int, b: Int) : Writer[String, Either[String, Int]] = (
divide[ErrorOr](a,b) match {
case Left(e) => Writer("Computation failed\n", Left(e))
case Right(n) => Writer(s"Divided $a by $b\n", Right(n))
}
)
def test = {
for(
a <- EitherT(logDivide(10,2));
b <- EitherT(logDivide(100,a));
c <- EitherT(logDivide(b, 4))
) yield c
}
def failTest = {
for(
a <- EitherT(logDivide(10,2));
b <- EitherT(logDivide(100,a));
c <- EitherT(logDivide(b, 0));
d <- EitherT(logDivide(c, 10))
) yield c
}
def main(args: Array[String]) : Unit = {
println(s"Success:\n$test\n\n")
println(s"Failure:\n$failTest")
}
/*
Success:
EitherT(WriterT((Divided 10 by 2
Divided 100 by 5
Divided 20 by 4
,Right(5))))
Failure:
EitherT(WriterT((Divided 10 by 2
Divided 100 by 5
Computation failed
,Left(division by zero))))
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.