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.
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.whenCompleteAsync
[1] is probably what you are looking for. [1] docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/…