Scala:如何确定失败的异常类型

j3d*_*j3d 10 error-handling scala exception

看看这段代码:

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

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

Did*_*ont 15

case Success(f) => 
case Failure(e: ExceptionType1) =>
case Failure(e: ExceptionType2) => 
case Failure(e) => // other
Run Code Online (Sandbox Code Playgroud)

要么

case Success(f) =>
case Failure(e) => e match {
   case e1: ExceptionType1 =>
   case e2: ExceptioNType2 =>
   case _ => 
}
Run Code Online (Sandbox Code Playgroud)

  • 不确定其中一个是否更标准.我相信我会使用第一个,除非在失败的情况下有一个共同的行为:你可以在失败案例中添加除e匹配之外的其他指令.两个看起来都很好,使用适合你的任何一个. (3认同)