【问题标题】:Scala: How to determine the exception type of a FailureScala:如何确定失败的异常类型
【发布时间】:2014-01-23 07:14:14
【问题描述】:

看这段代码sn-p:

userService.insert(user) match {
  case Success(f) => Logger.debug("User created successfully")
  case Failure(e) => {
     // how do I determine the type of `e`?
  }
}

如何确定Failure 包含的异常类型?我需要根据异常类型采取不同的操作。

【问题讨论】:

    标签: scala exception error-handling


    【解决方案1】:
    case Success(f) => 
    case Failure(e: ExceptionType1) =>
    case Failure(e: ExceptionType2) => 
    case Failure(e) => // other
    

    case Success(f) =>
    case Failure(e) => e match {
       case e1: ExceptionType1 =>
       case e2: ExceptioNType2 =>
       case _ => 
    }
    

    【讨论】:

    • @Didier,您觉得哪个更习惯用语?后者对我来说似乎更清楚,因为内部匹配仅与 Exceptions 相关。
    • 不确定其中一个是否更标准。我相信我会使用第一个,除非在失败的情况下存在常见行为:您可以在失败案例中放置除 e 匹配之外的其他指令。在我看来两者都很好,使用适合你的。
    • 我认为第一个更清晰,因为它避免了嵌套;即使存在共享行为,我也更倾向于使用case Failure(e: Ex1) | Failure(e: Ex2) => …
    • 可能存在一些异常行为共有的异常行为和各自特有的行为?
    猜你喜欢
    • 2013-02-03
    • 2018-01-17
    • 2020-03-24
    • 2010-10-08
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多