如何在Scala中编写处理未来异常的函数?

如何在Scala中编写处理未来异常的函数?,scala,Scala,在我的应用程序中,我多次以同样的方式处理未来的错误 例如,我: future map(r => println(r)) recover { case arithmeticException => log("arithmetic exception") case NonFatal(e) => log(e) } 如何从恢复部分提取方法,以便在其他地方重用 例如,我想做如下事情: def handleException(): PartialFunction[Throwab

在我的应用程序中,我多次以同样的方式处理未来的错误

例如,我:

future map(r => println(r)) recover { 
  case arithmeticException => log("arithmetic exception")
  case NonFatal(e) => log(e)
}
如何从恢复部分提取方法,以便在其他地方重用

例如,我想做如下事情:

def handleException(): PartialFunction[Throwable, Unit] = {
  case arithmeticException => log("arithmetic exception")
  case NonFatal(e) => log(e)
}
然后像这样使用它:

future map(r => println(r)) recover { handleException() }

我该怎么做?

有什么问题吗?您给出的示例效果很好。您也可以编写
recover handleException
而不是
recover{handleException()}
,无需像这样包装部分函数。@Naetmul您是对的。。。我的示例没有编译,因为handleException()中有一个错误的返回类型。…@Jesper-yep没有括号确实更好。
val handleException: PartialFunction[Throwable, Unit] = {
  case arithmeticException => log("arithmetic exception")
  case NonFatal(e) => log(e)
}

future.map(println).recover(handleException)