Last active
December 14, 2015 20:58
-
-
Save sam/5147497 to your computer and use it in GitHub Desktop.
An example of using Try (Scala 2.10 or greater required) to encourage error handling without bubbling up exceptions. Because you have to write the pattern anyway, you might as well fill in the details on what to do if the result isn't what you expected.
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 scala.util._ | |
import concurrent._ | |
import duration._ | |
import ExecutionContext.Implicits.global | |
import java.lang.ArithmeticException | |
// Catch the error in your Future and return it as a Failure: | |
def f(divisor:Int) = future { 100 / divisor } map(Success.apply) recover { | |
case e:ArithmeticException => Failure(e) | |
} | |
// Handle Success or Failure at the point of calling your Future: | |
def printResult(divisor:Int) = { | |
val result = f(divisor) map { | |
case Success(n) => println(n) | |
case Failure(e) => println("Bummer, something totes went wrong. :'(") | |
} | |
Await.result(result, 1 second) | |
} | |
// The above could also be written as: | |
def printResult(divisor:Int) = Await.result(f(divisor) map { | |
case Success(n) => println(n) | |
case Failure(e) => println("Bummer, something totes went wrong. :'(") | |
}, 1 second) | |
// Or even: | |
def printResult(divisor:Int) = (Await.result(_:Future[Unit], 1 second)) { | |
f(divisor) map { | |
case Success(n) => println(n) | |
case Failure(e) => println("Bummer, something totes went wrong. :'(") | |
} | |
} | |
// | |
printResult(0) | |
printResult(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment