Created
July 28, 2019 05:39
-
-
Save justinhj/de8c7f2438c7d41d66fc4961854e5437 to your computer and use it in GitHub Desktop.
Error handling and logging
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
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