在scala中如何包装PartialFunction?

时间:2015-04-02 17:23:31

标签: scala

在scala中,Futures有一种带有PartialFunction的救援功能。如果Future使用响应解析但在发生故障时调用此代码,则会跳过此代码。

我想简单地将partial函数包装在代理中,该代理总是执行写入stat计数器的代码。起初我以为我会创建另一个PartialFunction,但很快意识到这对isDefined不起作用,然后应用,因为我真的希望每次调用它。

如何处理PartialFunction的代理,以便在Future有异常时始终调用我的代码?

1 个答案:

答案 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上的FuturePartialFunction[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}}