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] = {
case ex: Exception =>
println(whichFuture +": "+ ex.getMessage)
}
f1.onFailure(errorLogging("f1"))
f2.onFailure(errorLogging("f2"))
val res = for {
res1 <- f1
res2 <- f2
} yield {
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.
source
share