在scala中,Futures有一种带有PartialFunction的救援功能。如果Future使用响应解析但在发生故障时调用此代码,则会跳过此代码。
我想简单地将partial函数包装在代理中,该代理总是执行写入stat计数器的代码。起初我以为我会创建另一个PartialFunction,但很快意识到这对isDefined不起作用,然后应用,因为我真的希望每次调用它。
如何处理PartialFunction的代理,以便在Future有异常时始终调用我的代码?
答案 0 :(得分:5)
总结评论:当onFailure
失败时,您可以使用Future
回调执行一些副作用代码(日志记录)。
val future = Future(1 / 0)
future.onFailure {
case _ => println("I have seen the Future, and it doesn't look good.")
}
正如@cmbaxter所说,您也可以使用andThen
上的Future
,PartialFunction[Try[A], B]
接受Future
并返回原始 andThen
。因此,您可以使用recover
应用副作用函数,然后使用Future(1 / 0)
.andThen { case Failure(_) => println("Future failed.") }
.recover { case e: ArithmeticException => 0 }
.andThen { case Failure(_) => println("Tried to recover, and still failed.") }
。你甚至可以多次链接它们。
object FutureLogger {
def apply[A](a: => A): Future[A] = Future(a).andThen {
case Failure(_) => println("FAILURE")
}
}
或者总是包含它的帮助者:
{{1}}