我有一个从 scala 异步调用的网络服务。我想匹配并处理一些特定的故障代码,这些故障代码可以由 recover
block 中的 web 服务返回。
该错误作为一个 SoapFault
实例返回,该实例包含在一个额外的异常中,因此基本上我需要匹配所有异常
- 有一个原因是
SoapFault
的一个实例
SoapFault
消息符合我的要求
到目前为止,我有这个工作但很麻烦:
call map { result =>
// handle success
} recover {
case e: Exception if e.getCause != null && e.getCause.isInstanceOf[SoapFault] && e.getCause.asInstanceOf[SoapFault].getMessage == "INVALID_INPUT" => {
// handle error
}
case e: Exception if e.getCause != null && e.getCause.isInstanceOf[SoapFault] && e.getCause.asInstanceOf[SoapFault].getMessage == "SERVER_BUSY" => {
// handle error
}
}
我怎样才能以更好的方式减少重复?
最佳答案
您可以创建自己的 Extractor Object .像(未经测试):
object FaultWithMessage {
def apply(message: String) = new Object() {
def unapply(t: Throwable): Boolean = t match {
case e: Exception if e.getCause != null &&
e.getCause.isInstanceOf[SoapFault] &&
e.getCause.asInstanceOf[SoapFault].getMessage == message => true
case _ => false
}
}
... recover {
case FaultWithMessage("INVALID_INPUT")() =>
//handle that one
case FaultWithMessage("SERVER_BUSY")() =>
//handle that one
...
}
关于java - 如何在 Scala 中更好地匹配 Java 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27399856/