Skip to content

Instantly share code, notes, and snippets.

@angelcervera
Created February 1, 2020 10:43
Show Gist options
  • Select an option

  • Save angelcervera/e792cbcbb89f21b1cd6e7216e310106d to your computer and use it in GitHub Desktop.

Select an option

Save angelcervera/e792cbcbb89f21b1cd6e7216e310106d to your computer and use it in GitHub Desktop.
Exception handling to Either
import org.scalatest.{Matchers, WordSpecLike}
import scala.util.{Failure, Success, Try}
object ExceptionHandlingExamples {
case class CaseClass(a: Int, b: Int)
def parseUsingMatchOnTry(str: String): Either[String, CaseClass] =
str.split("_") match {
case Array(a, b) =>
Try(CaseClass(a.toInt, b.toInt)) match {
case Success(c) => Right(c)
case Failure(e) => Left(s"Error parsing ${str} => ${e.getMessage}")
}
case _ => Left(s"[${str}] is not a valid format for a CaseClass")
}
def parseUsingEitherIsomorphism(str: String): Either[String, CaseClass] =
str.split("_") match {
case Array(a, b) =>
Try(CaseClass(a.toInt, b.toInt)).toEither.left
.map(e => s"Error parsing ${str} => ${e.getMessage}")
case _ => Left(s"[${str}] is not a valid format for a CaseClass")
}
def parseUsingFold(str: String): Either[String, CaseClass] =
str.split("_") match {
case Array(a, b) =>
Try(CaseClass(a.toInt, b.toInt))
.fold(
e => Left(s"Error parsing ${str} => ${e.getMessage}"),
tileIdx => Right(tileIdx)
)
case _ => Left(s"[${str}] is not a valid format for a CaseClass")
}
}
class ExceptionHandlingExamplesTest extends WordSpecLike with Matchers {
import ExceptionHandlingExamples._
"ExceptionHandlingExamples" when {
"uses match on Try" in {
parseUsingMatchOnTry("1_2") shouldBe Right(CaseClass(1, 2))
parseUsingMatchOnTry("X_Y") shouldBe Left(
"Error parsing X_Y => For input string: \"X\""
)
}
"uses either isomorphism" in {
parseUsingEitherIsomorphism("1_2") shouldBe Right(CaseClass(1, 2))
parseUsingEitherIsomorphism("X_Y") shouldBe Left(
"Error parsing X_Y => For input string: \"X\""
)
}
"uses fold" in {
parseUsingFold("1_2") shouldBe Right(CaseClass(1, 2))
parseUsingFold("X_Y") shouldBe Left(
"Error parsing X_Y => For input string: \"X\""
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment