Skip to content

Instantly share code, notes, and snippets.

@quelgar
Last active August 29, 2015 14:25
Show Gist options
  • Save quelgar/7c957d5801dfabf65498 to your computer and use it in GitHub Desktop.
Save quelgar/7c957d5801dfabf65498 to your computer and use it in GitHub Desktop.
Generically convert thrown exceptions to an Either
/**
* Catch exceptions to create an `Either` value.
*
* Useful when you want to deal an API that reports failure conditions using
* exceptions. This method allows catching exceptions and converting them to
* `Left` values.
*
* An advantage vs using `scala.util.Try` is that you have full control over
* which exceptions are caught.
*
* @param block The block of code to catch exceptions from.
* @param catcher The exception catcher. Any exceptions not caught by
* this will be thrown as normal.
* @tparam A The type of the error value returned if an exception is caught.
* @tparam B The type of the result if no exceptions are thrown.
* @return The block's value if no exceptions are thrown, or an error value
* if an exception is thrown and caught by `catcher`.
*/
def eitherCatch[A, B](block: => B)(catcher: PartialFunction[Throwable, A]): Either[A, B] = {
try {
Right(block)
}
catch catcher.andThen(Left(_))
}
object Example {
val result: Either[String, Array[Byte]] = eitherCatch {
Files.readAllBytes(file)
} {
case e: IOException => e.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment