Futures for understanding. Failure Detection

I use Scala. To understand, wait until several futures are executed. But I also want to process onFailure(I want to write an error message for registration). How can i achieve this?

This is my code:

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

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

If you want to write an error message to a log file, you can simply link the error log to the part onFailure:

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 will print:

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

As you can see, the problem is that things can happen out of order, and logging can be far from when Exception will eventually be logged.

+2
source

All Articles