devoured elysium
devoured elysium

Reputation: 105067

Using Try() mapping it into an Option with Some(errorMsg) in case of error

I wanted to replace the below code with something using either Either or Try(). With vanila scala, is there any straightforward way of making the below code more concise? What I seem to want is to have something like an hypotheticalTry(code).toOption.invert.

def calculateSomething(): Option[String] =
    try {
      // execute some side effects
      None      
    } catch {
      case t:Throwable => Some("some error msg")
    }

Thanks

Upvotes: 1

Views: 43

Answers (1)

MAlo
MAlo

Reputation: 46

You could use the failed method of Try which is kind of like the invert method you're looking for :

val option = Try(code).failed.toOption

The you can just map over it if you only want the error message:

option.map(_.getMessage)

You can getMessage on the throwable or simply have a function that returns a constant (like _ => "my error message") if you want a custom message.

Upvotes: 3

Related Questions