Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Try/Future, wrapping the exception in case of failure

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.

like image 808
Sebastien Lorber Avatar asked Dec 13 '13 15:12

Sebastien Lorber


People also ask

How do you handle exceptions in Scala?

However, Scala doesn't actually have checked exceptions. When you want to handle exceptions, you use a try{...} catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.

How does Try catch work in Scala?

Scala provides try and catch block to handle exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need.

When to use Try in Scala?

Try was introduced in Scala 2.10 and behaves as a mappable Either without having to select right or left. You can see how, instead of using explicit try and catch to treat exceptions, Try is used to encapsulate the operation which is always an instance of either Success or Failure.


1 Answers

With recover:

val c = scala.util.Try(doSomething).recover { 
    case e: DoSomethingException => throw new BusinessException
}
like image 63
barczajozsef Avatar answered Oct 20 '22 10:10

barczajozsef