fxp
fxp

Reputation: 7082

How to handle AskTimeoutException?

I'm trying to call a actor to do something time consuming. The caller set a timer with 5 sec. But I can't handle the timeout exception with try/catch.

return async(Akka.asPromise(ask(myActor, "hello", uploadImageTimeout)).map(new Function<Object, Result>() {
@Override
public Result apply(Object response) {
return ok("Done");
}
}));

Upvotes: 2

Views: 1189

Answers (2)

gavioto
gavioto

Reputation: 1745

Using Play 2.2.1 (and Akka 2.2) requires minor changes in solution. Source code test are the best site to find responses. I found mine here https://github.com/akka/akka/blob/f1edf789798dc02dfa37d3301d7712736c964ab1/akka-docs/rst/java/code/docs/future/FutureDocTest.java

 @Test
 public void useRecover() throws Exception {
   //#recover
   final ExecutionContext ec = system.dispatcher();
   Future<Integer> future = future(new Callable<Integer>() {
      public Integer call() {
        return 1 / 0;
      }
   }, ec).recover(new Recover<Integer>() {
      public Integer recover(Throwable problem) throws Throwable {
        if (problem instanceof ArithmeticException)
          return 0;
        else
          throw problem;
      }
   }, ec);

   future.onSuccess(new PrintResult<Integer>(), system.dispatcher());
     //#recover
     int result = Await.result(future, Duration.create(5, SECONDS));
     assertEquals(result, 0);
  }

Upvotes: 0

tejas
tejas

Reputation: 627

One thing you can do is to "recover" from the exception right inside the Akka future:

return async(Akka.asPromise(ask(myActor, "hello", uploadImageTimeout).recover(
    new Recover<Object>() {
        @Override
        public Object recover(Throwable t) throws Throwable {
            if( t instanceof AskTimeoutException ) {
                Logger.error("Got exception: ", t);
                return internalServerError("Timeout");
            }
            else {
                Logger.error("Got exception: ", t);
                return internalServerError("Got Exception: " + t.getMessage());
            }
        }
    })
).map(new Function<Object, Result>() {
    @Override
    public Result apply(Object response) {
        if( response instanceof Result ) {
            // Result objects are returned by the recover handler above
            return (Result)response;
        }
        else {
            return ok(doSomethingWithResponse(response));
        }
    }
}));

Upvotes: 3

Related Questions