Search code examples
javajava-11java-http-client

How to handle errors when executing an async request with HTTP Java Client?


I'm using the new Java 11 HTTP Client. I have a request like:

httpClient.sendAsync(request, discarding())

How to add a handler for HTTP errors? I need to log errors but I want to keep the request async.

Currently, HTTP errors like 400 or 500, are silent. I'd like to log the status code and response body on those occasions. I suppose the CompletableFuture is just like a promise, so the reply is not available there yet.


Solution

  • You just need to register a dependent action with the completable future returned by HttpClient::sendAsync

    Here is an example:

    public static void main(String[] argv) {
        var client = HttpClient.newBuilder().build();
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://www.example.com/"))
                .build();
        var cf = client.sendAsync(request, HttpResponse.BodyHandlers.discarding())
                .thenApplyAsync((resp) -> {
                    int status = resp.statusCode();
                    if (status != 200) {
                        System.err.println("Error: " + resp.statusCode());
                    } else {
                        System.out.println("Success: " + resp.statusCode());
                    }
                    return resp;
                });
        cf.join(); // prevents main() from exiting too early
    }