java - 如何在 Scala 中更好地匹配 Java 类型?

标签 java scala

我有一个从 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/

相关文章:

scala - 如何制作 scala actor 'wait for the signal' 但不丢失任何消息?

scala - 如何找到 spark RDD/Dataframe 大小?

scala - 无法在抽象类中导入案例类

java - Android fragment NullPointerException 错误

java - 将单个 senerio 与 ANTLR 匹配并跳过其他所有噪音

scala - 用于 REST 轮询的 Akka

scala - 在函数式编程中查找列表列表中元素的位置

java - 在哪里可以找到实现 org.osgi.service.log.LoggerFactory 服务的包?

java - Lucene——过滤特定字段的文档

java - 如何将对象反序列化为同名的新对象?