理解中的未来。检测失败

时间:2015-06-10 14:20:19

标签: scala future

我使用Scala进行理解,等到几个期货将被执行。但是我也想处理onFailure(我想写错误消息来记录)。我怎么能实现它?

这是我的代码:

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

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

1 个答案:

答案 0 :(得分:2)

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

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

相关问题