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.

3
  • 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
    Commented Oct 26, 2021 at 12:09
  • I would like to call my custom code when I have exception/timeout. Commented Oct 27, 2021 at 13:06
  • Then whenCompleteAsync [1] is probably what you are looking for. [1] docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/…
    – daniel
    Commented Oct 28, 2021 at 9:17

1 Answer 1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.