Scala: How to determine the exception type of a Failure
Asked Answered
S

2

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.

Subtropics answered 5/1, 2014 at 23:25 Comment(0)
P
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 _ => 
}
Pendulum answered 5/1, 2014 at 23:28 Comment(4)
@Didier, which seems more idiomatic to you? The latter seems clearer to me since the inner match relates to Exceptions only.Afterimage
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.Pendulum
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) => ….Adequate
There might be some behavior common to both exception and some specific to each?Pendulum
T
0

or

case Success(f) =>
case Failure(e @ _: ExceptionType1) =>
case Failure(e @ _: ExceptionType2 | ExceptionType3) =>
case Failure(e) =>
Tome answered 15/9, 2023 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.