如何处理AskTimeoutException?

时间:2012-03-23 09:31:12

标签: playframework-2.0

我试图让一个演员做一些耗费时间的事情。 呼叫者设置一个计时器,持续5秒。但我无法使用try / catch处理超时异常。

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

2 个答案:

答案 0 :(得分:3)

你可以做的一件事就是从Akka未来的异常中“恢复”:

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));
        }
    }
}));

答案 1 :(得分:0)

使用Play 2.2.1(和Akka 2.2)需要对解决方案进行细微更改。源代码测试是查找响应的最佳站点。我在这里找到了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);
  }