Last active
August 29, 2015 14:25
-
-
Save quelgar/7c957d5801dfabf65498 to your computer and use it in GitHub Desktop.
Generically convert thrown exceptions to an Either
This file contains 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
/** | |
* 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