Continue when Future.failed (new exception ("")) returns to Scala

How can I handle if the future returns a failed exception?

The scenario is that my code calls getValue() , matches the result with verifyValue() , and then I want to be able to handle the case where the result of getValue () is Future.failed(new Exception("message")) . However, when I run this, if the result of getValue () is a bad future, it just throws an exception rather than handling it.

Does anyone have any suggestions on how I will do this?

 def method(): Future[JsObject] = { getValue().flatMap(verifyValue(_)) } def getValue(): Future[JsObject] = { try { value1 <- getValue1() value2 <- getValue2(value1) } yield { value2 } } def verifyValue(result: Any): Future[JsObject] = { result match { case e: Exception => getValue() case json: JsObject => Future.successful(json) } } 

Update: I don’t think I made it clear with the original question, but the reason I am planning the value is because I don’t want to explicitly wait for any of the futures in my code, and therefore I don’t want to use Future.onComplete {} functions for determining the value.

Update 2: Another thing that may be unclear is that if it throws an exception, I want to call another method. I don’t want it to simply handle the exception, it will register an exception and then call another method whose return value is of the same type as getValue ().

+7
scala
source share
3 answers

As a result, I used the Future.fallbackTo () method.

 def method(): Future[JsObject] = { getValue().fallbackTo(method1()).fallbackTo(method2()).fallbackTo(method3()) } 

If the future from the first getValue() fails, it will call method1() . If this also fails, it will call method2() , etc. If one of the methods succeeds, it will return this value. If none of the methods is executed, it will return a failed future from getValue() .

This solution is not ideal, as I would rather include all four exceptions that were thrown if all attempts failed, but it at least allows me to repeat the getValue() method.

+3
source share

Use recover or recoverWith

recover or recoverWith is called when the future fails with an exception. In the recovery block, you can specify an alternative value.

recoverWith unlike recover accepts the future of something

 getValue().recover { case th => //based on the exception type do something here defaultValue //returning some default value on failure } 
+6
source share
 import scala.util.{Success, Failure} f.onComplete { case Success(value) => // do sth with value case Failure(error) => // do sth with error } 

You can use onComplete in the () method, see the link below for other options:

http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future.html

+1
source share

All Articles