4

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.

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
  • 2
    Can you specify what exactly do you mean by *HTTP errors* in the context? The Java API returns you a `CompletableFuture>` what is it that you want o to infer from it or is there something missing there is what you're asking for? – Naman May 24 '19 at 10:10
  • please check the edits – Luís Soares May 24 '19 at 10:32

1 Answers1

3

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
}
daniel
  • 2,665
  • 1
  • 8
  • 18
  • doesn't the `join` make it blocking again? – Luís Soares May 24 '19 at 15:40
  • Yes - it does, this is just to prevent the main() method from exiting before the request has completed and the response has been received. – daniel May 24 '19 at 17:05
  • But if my application is long running I don't need right? It it's blocking I would just use `send` rather than `sendAsync` – Luís Soares May 24 '19 at 17:09
  • 1
    Right. Here it's a simple program that just sends one request. The client is fully asynchronous. Even connecting to the server is asynchronous. Which means that depending on how fast (or slow) the server responds, the program might exit before having sent, received, or printed anything, if you don't force it to wait long enough. – daniel May 24 '19 at 17:12