Futures in For comprehension. Detect failure

339 views Asked by At

I'm using Scala's For comprehension to wait until several futures will be executed. But I want also to handle the onFailure (I want to write error message to log). How I can achieve it?

This is my code:

val f1 = Future {...}
val f2 = Future {...}

for { 
  res1 <- f1
  res2 <- f2
} {
  // this means both futures executed successfully
  process(res1, res2)
} 
1

There are 1 answers

0
Akos Krivachy On

If you only want to write an error message to a log file you can just chain your error logging onto the onFailure part:

val f1 = Future.successful("Test")
val f2 = Future.failed(new Exception("Failed"))

def errorLogging(whichFuture: String): PartialFunction[Throwable, Unit] = {
  // Here you have the option of matching on different exceptions and logging different things
  case ex: Exception =>
    // Do more sophisticated logging :)
    println(whichFuture +": "+ ex.getMessage)
}

f1.onFailure(errorLogging("f1"))
f2.onFailure(errorLogging("f2"))

val res = for {
  res1 <- f1
  res2 <- f2
} yield {
   // this means both futures executed successfully
  println(res1 + res2)
}

Await.result(res, Duration.Inf)

This would print out:

Exception in thread "main" java.lang.Exception: Failed
   at [...]
f2: Failed

As you see the issue with this is that things might happen out of order and the logging might be far away from when the Exception is eventually logged.