Question

Suppose I have a method def doSomething: String which can raise a DoSomethingException if something goes wrong.

If I write Try(doSomething), is there a simple way to map the exception without recovering it?

Basically, I want the failure to become a BusinessException caused by the DoSomethingException.

I know the code to do this is very simple, but isn't there any built-in operator to do so? It seems a very common operation but I can't find anything in the API.

Was it helpful?

Solution 2

You can use transform

val t = Failure(new DoSomethingException)
val bt = t.transform(s => Success(s), e => Failure(new BusinessException))

OTHER TIPS

With recover:

val c = scala.util.Try(doSomething).recover { 
    case e: DoSomethingException => throw new BusinessException
}

You can also use recoverWith:

Try {
    doSomething
} recoverWith { 
    case e: DoSomethingException => Failure(new BusinessException)
}

You can as well match on Try using PartialFunction (and unwrap the value if there were no failures):

Try(doSomething) match {
    case Success(result) => result
    case Failure(throwable) => new BusinessException(throwable)
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top