0

I want to use Java Http Client: java.net.http.HttpClient in asynchronous way. When I receive http response (any http code) or timeout I want to execute some custom Java code. I struggle to complete the body of error handling.

CompletableFuture<HttpResponse<String>> response =
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  .thenApplyAsync(body -> {
    System.out.println("Request finished");
    return body;
  })
  .exceptionallyAsync(exception -> {

     // WHAT TO RETURN HERE ?      
  });

The method: exceptionallyAsync returns: CompletableFuture<T>, but I do not know how to complete this method.

Can you please help me to finish this method? I cannot find example in GitHub or Google.

daniel
  • 2,665
  • 1
  • 8
  • 18
Hollow.Quincy
  • 547
  • 1
  • 7
  • 14
  • `exceptionallyAsync` may not be the method you need. This method is useful if you want to return an alternate result when an exception happens. But is it what you want to do? Please clarify your question to explain what you want to do when an exception happens. – daniel Oct 26 '21 at 12:09
  • I would like to call my custom code when I have exception/timeout. – Hollow.Quincy Oct 27 '21 at 13:06
  • Then `whenCompleteAsync` [1] is probably what you are looking for. [1] https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html#whenCompleteAsync(java.util.function.BiConsumer) – daniel Oct 28 '21 at 09:17

1 Answers1

0

You can use

.exceptionally(this::handlError)

If this is your response handler with a method like:

    private Void handlError(Throwable ex) {
        System.out.println(ex.toString());
        return null;
    }
emicklei
  • 1,321
  • 11
  • 10