【问题标题】:Futures in For comprehension. Detect failureFor 理解中的期货。检测故障
【发布时间】:2015-06-10 23:45:27
【问题描述】:

我正在使用 Scala 的 For 理解来等到几个期货将被执行。但我也想处理onFailure(我想将错误消息写入日志)。我怎样才能实现它?

这是我的代码:

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

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

【问题讨论】:

  • onFailure 是一个处理程序,它可以“链接”到仅在失败时运行的未来,因此您可以在 for 理解之前执行 f1.onFailure(// log failure) ,然后像下面一样执行其余操作你的代码中有它。

标签: scala future


【解决方案1】:

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

正如您所看到的,问题是事情可能会发生混乱,并且日志记录可能与最终记录异常时相距甚远。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多