j3d
j3d

Reputation: 9724

Scala: How to determine the exception type of a Failure

Look at this code snippet:

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

How do I determine the type of the exception contained by Failure? I need to take different actions depending on the exception type.

Upvotes: 11

Views: 5460

Answers (2)

Julia
Julia

Reputation: 194

or

case Success(f) =>
case Failure(e @ _: ExceptionType1) =>
case Failure(e @ _: ExceptionType2 | ExceptionType3) =>
case Failure(e) =>

Upvotes: 0

Didier Dupont
Didier Dupont

Reputation: 29528

case Success(f) => 
case Failure(e: ExceptionType1) =>
case Failure(e: ExceptionType2) => 
case Failure(e) => // other

or

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

Upvotes: 19

Related Questions