Scala Try 和不同的失败案例

标签 scala

此代码作为异常(exception)返回“我失败了”。

  Try({
    throw new Exception()
  }) match {
    case Failure(e) => println("I've failed")
    case Success(s) => println("I've succeeded")
  }

但是如果我有不同的异常怎么办,例如:

  Try({
    if(someBoolean) {
      throw new DifferentException()
    } else {
      throw new Exception()
    }
  }) match {
    case Failure(e) => println("I've failed")
    case Success(s) => println("I've succeeded")
  }

如何更改匹配语句,以便我们对 ExceptionDifferentException 有不同的情况?

我知道我可以做到:

  Try({
    if(true) {
      throw new DifferentException()
    } else {
      throw new Exception()
    }
  }) match {
    case Failure(e) if e.isInstanceOf[DifferentException] => println("I've failed differently")
    case Failure(e) if e.isInstanceOf[Exception]          => println("I've failed")
    case Success(s) => println("I've succeeded")
  }

这是最好的,即最不冗长的方式吗?

[编辑]

感谢 Ashesh。对我来说,最不冗长的是:

case class DifferentException() extends Exception() {}

Try({
  if(someBoolean) { 
    throw new DifferentException
  } else { 
    throw new Exception
  } 
}) match { 
  case Failure(DifferentException()) => println("I've failed differently")
  case Failure(e)                    => println("I've failed")
  case Success(s)                    => println("I've succeeded")
}

最佳答案

您可以为任何异常类型(无论是否为案例类)匹配Failure(e: ExceptionType),无需创建您自己的异常类型或两个模式匹配表达式:

def printResult(action: => Unit) = {
  Try(action) match {
    case Failure(e: IllegalArgumentException) => println("illegal arg exception")
    case Failure(e) => println("other exception")
    case _ => println("success")
  }
}

printResult(throw new IllegalArgumentException)  // prints "illegal arg exception"
printResult(throw new RuntimeException)          // prints "other exception"
printResult(1)                                   // prints "success"

关于Scala Try 和不同的失败案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39426645/

相关文章:

使用泛型和案例类方法的 Scala 特征

json - 隐式范围内的 models.AccountStatus 没有 play.api.libs.json.Format 的实例

scala - 类型不匹配;找到 : edu. stanford.nlp.util.CoreMap => 需要单位 : java. util.function.Consumer[_> : edu. stanford.nlp.util.CoreMap]

scala - 在 Scala Play Framework v2.6.x 中出现 cors 错误

scala - 在Spark DataFrame中对结构数组进行排序

java - Kafka的分区选择算法

json - Scala 2.10 + Json 序列化和反序列化

scala - 如何证明两种类型的等价性以及签名是单一存在的?

scala - SBT 在 Sources 中查找子类型

scala - 从 DataFrame 到 Array 的不同值