【发布时间】:2020-09-13 06:34:37
【问题描述】:
我有部分方法 defaultRecover 帮助从异常中恢复:
def getName(length: Int): Future[String] = {
if (length > 0)
Future.successful("john")
else
Future.failed(new RuntimeException("failed"))
}
def defaultRecover: PartialFunction[Throwable, String] = {
case _ => "jane"
}
// easy and working
val res = getName(0) recover {
defaultRecover
}
现在的问题。我定义了第二种恢复方法emergencyRecover,我想根据另一个调用的结果选择使用哪种恢复方法-isEmergency()。
def emergencyRecover: PartialFunction[Throwable, String] = {
case _ => "arnold"
}
// simplified - this actually calls REST API
def isEmergency(): Future[Boolean] = {
Future.successful(true)
}
// type mismatch
// required: PartialFunction[Throwable,String]
// found : Future[PartialFunction[Throwable,String]]
val res = getName(0) recover {
isEmergency() map {
case false => defaultRecover
case true => emergencyRecover
}
}
但是我遇到了类型不匹配。我怎样才能实现这种错误处理?除了恢复,我还需要使用其他方法吗?
【问题讨论】: