Skip to content

Instantly share code, notes, and snippets.

@petrovg
Created May 13, 2014 16:43
Show Gist options
  • Select an option

  • Save petrovg/dbdaf451901ff0bef2e3 to your computer and use it in GitHub Desktop.

Select an option

Save petrovg/dbdaf451901ff0bef2e3 to your computer and use it in GitHub Desktop.
Scala future error recovery/handling
object TMP extends App {
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
def b1 = {
val f: Future[Int] = scala.concurrent.future { 100 }
val r = Await.result(f, 1.second)
println(":> " + r)
}
def b2 = {
val f: Future[Int] = scala.concurrent.future { throw new Exception("Borken") }
val r = Await.result(f, 1.second)
println(":> " + r)
}
def b3 = {
val f: Future[Int] = scala.concurrent.future { throw new Exception("Borken") } recover { case e => println(":< " + e); 0 }
val r = Await.result(f, 1.second)
println(":> " + r)
}
def b4 = {
val f: Future[Int] = scala.concurrent.future { throw new Exception("Borken") } recover { case e => throw new Exception("Couldn't get the int", e) }
val r = Await.result(f, 1.second)
println(":> " + r)
}
def b5 = {
val f: Future[Int] = scala.concurrent.future { if (math.random < .5) 76 else throw new Exception("Bork") } map (_ / 2) recover { case e => throw new Exception("Couldn't get the int", e) }
val r = Await.result(f, 1.second)
println(":> " + r)
}
b5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment