11

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.

2 Answers 2

19
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 _ => 
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Didier, which seems more idiomatic to you? The latter seems clearer to me since the inner match relates to Exceptions only.
Not sure if one of them is more standard. I believe I would use the first one, except if there is a common behavior in case of failure: you may put other instructions than the e match in the Failure case. Both look fine to me, use whichever one suits you.
I think the first is much clearer as it avoids nesting; even in the presence of shared behaviour I'd be more inclined to use case Failure(e: Ex1) | Failure(e: Ex2) => ….
There might be some behavior common to both exception and some specific to each?
0

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.