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

Luís Soares :

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.

daniel :

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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148915&siteId=1
Recommended