Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created July 24, 2016 13:53
Show Gist options
  • Save JoolsF/168a39cf466f5b8219a76b1a7f343494 to your computer and use it in GitHub Desktop.
Save JoolsF/168a39cf466f5b8219a76b1a7f343494 to your computer and use it in GitHub Desktop.
Exception handling with Either 1
import scala.util.control.Exception._
val r = new java.util.Random
def randomBoolean(exceptionChance: Int) = r.nextInt(exceptionChance) == 0
def handling[Ex <: Throwable, T](exType: Class[Ex])(block: => T): Either[Ex, T] =
catching(exType).either(block).asInstanceOf[Either[Ex, T]]
def exceptionOrString = if(randomBoolean(4)) throw new RuntimeException("This is a runtime exception") else "Phew! You got a string"
val handleExample: Either[RuntimeException, String] = handling(classOf[RuntimeException])(exceptionOrString)
handleExample match {
case Left(exception) => println(exception)
case Right(string) => println(string)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment