斯卡拉 – 期待理解.检测失败

我正在使用
Scala的For comprehension等到几个期货将被执行.但我也想处理onFailure(我想写错误信息到日志).我怎么能实现它?

这是我的代码:

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

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

最佳答案 如果您只想将错误消息写入日志文件,则可以将错误记录链接到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)

这将打印出来:

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

正如您所看到的,问题是事情可能无序发生,并且日志记录可能远离最终记录异常的时间.

点赞