如何处理异步块java中的异常

时间:2016-09-01 17:01:13

标签: java playframework

我一个接一个地发出2个https请求。我希望在发出另一个请求之前,在第一个请求失败的情况下返回错误状态。

private CompletionStage<WSResponse> reverseGeocode(Double latitude, Double longitude) throws AuthenticationException {
    WSRequest complexRequest = ws.url(SECO_URL);

    return complexRequest.post(GRANT_TYPE + "=" + PASSWORD + "&" + USERNAME + "=" + SECO_USERNAME + "&" + PASSWORD
            + "=" + SECO_PASSWORD)
            .thenCompose(res -> {
                String authToken;
                try {
                    authToken = res.asJson().findValue("access_token").toString().replace("\"", "");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    LOG.error(e.getMessage() + e.toString());
                    throw new AuthenticationException("Not able to authenticate user");
                }
                String url = configuration.getString("host.lbsUrl") + "/rgc/json?lat=" 
                        + latitude + "&lon=" + longitude;
                WSRequest requestToReverseGeocode = ws.url(url)
                        .setHeader(API_KEY, ST_SECO_X_API_KEY)
                        .setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE)
                        .setHeader(AUTHORIZATION, "Bearer " + authToken);
                return requestToReverseGeocode.get();
            });

}

上面的函数给出了错误,认证错误未处理。在这种情况下如何返回错误?

上面的代码没有编译,错误是

play.sbt.PlayExceptions$CompilationException: Compilation error[unreported exception org.apache.http.auth.AuthenticationException; must be caught or declared to be thrown]
    at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
    at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
    at scala.Option.map(Option.scala:145)
    at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:49)
    at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:44)
    at scala.Option.map(Option.scala:145)
    at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:44)
    at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:40)
    at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
    at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
    at scala.util.Either$LeftProjection.map(Either.scala:377)
    at play.sbt.run.PlayReload$.compile(PlayReload.scala:17)
    at play.sbt.run.PlayRun$$anonfun$playRunTask$1$$anonfun$apply$2$$anonfun$apply$3$$anonfun$2.apply(PlayRun.scala:61)
    at play.sbt.run.PlayRun$$anonfun$playRunTask$1$$anonfun$apply$2$$anonfun$apply$3$$anonfun$2.apply(PlayRun.scala:61)
    at play.runsupport.Reloader$$anonfun$reload$1.apply(Reloader.scala:339)
    at play.runsupport.Reloader$$anon$3.run(Reloader.scala:44)
    at java.security.AccessController.doPrivileged(Native Method)
    at play.runsupport.Reloader$.play$runsupport$Reloader$$withReloaderContextClassLoader(Reloader.scala:40)
    at play.runsupport.Reloader.reload(Reloader.scala:337)
    at play.core.server.DevServerStart$$anonfun$mainDev$1$$anon$1$$anonfun$get$1.apply(DevServerStart.scala:118)
    at play.core.server.DevServerStart$$anonfun$mainDev$1$$anon$1$$anonfun$get$1.apply(DevServerStart.scala:116)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:405)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)

1 个答案:

答案 0 :(得分:3)

您可以使用exceptionally来捕捉可能出现的任何错误。

return complexRequest.post()
    .thenCompose(res -> {
        if (someCondition) throw new Step1Exception("Step 1 failed");
        // (...)    
    }).thenCompose(res -> {
        if (someAnotherCondition) throw new StepNException("Step N failed");
        // (...)    
    }).exceptionally(e -> ok("Got an error: " + e.getMessage()));

请注意,如果someCondition为真,则不执行第二个thenCompose