Sub topic 9
Handling failures: non-2xx statuses, IOException and interruption
This chapter assumes you can already build an HttpClient, send a request with send, and read statusCode() and body(). It also assumes you know Java checked exceptions and the basic HTTP status classes (2xx, 3xx, 4xx, 5xx).
Two kinds of failure
HttpClient reports problems in two different ways.
- The server answered, but not with success. A 404 or 500 is a valid HTTP response.
sendreturns it normally and throws nothing. - No usable response arrived. The connection failed, the timeout fired, the TLS handshake broke, or your thread was interrupted. These arrive as exceptions.
Most bugs in HTTP client code come from treating the first kind as if it were the second. A program that only has a catch block will happily parse the HTML of a 500 error page as if it were data.
Non-2xx statuses are your job to check
After send returns, check the status before you use the body.
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new IllegalStateException(
"Unexpected status " + status + ": " + response.body());
}Three details matter here.
- The body still arrives. With
BodyHandlers.ofString(), an error response has its body read like any other. APIs often put a useful JSON error message there, so log it. - Redirects count as non-2xx. The default redirect policy is
NEVER, so a 301 or 302 comes back as an ordinary response. If you expect redirects, setfollowRedirectson the client (see the redirects chapter). - Different classes need different reactions. A 4xx means your request was wrong, so repeating it will not help. A 5xx or 429 may be temporary, which matters for the retries chapter.
The exceptions send can throw
send declares two checked exceptions: IOException and InterruptedException. Both need handling, and the order of the catch blocks matters.
| Exception | Typical cause | Retry sensible? |
|---|---|---|
| `HttpConnectTimeoutException` | The connect timeout expired before a connection opened | Often |
| `HttpTimeoutException` | The per-request timeout expired | Depends on the method |
| `ConnectException` | Connection refused, or the host could not be reached | Often |
| `SSLException` and subclasses | Bad certificate or handshake failure | No |
| other `IOException` | Connection reset, or the stream ended early | Depends |
| `InterruptedException` | Another thread interrupted the waiting thread | No, stop |
HttpConnectTimeoutException extends HttpTimeoutException, which extends IOException. Put the most specific type first, or the compiler rejects the later catch block as unreachable.
Some problems are unchecked and appear before any network call. URI.create throws IllegalArgumentException for a malformed address, and building a request with a non-HTTP scheme fails the same way. These are programming errors. Fix the code instead of catching them.
Interruption: restore the flag
send blocks the calling thread. If another thread calls interrupt() on it, send throws InterruptedException and clears the thread's interrupt flag. Swallowing the exception hides the cancellation request from the rest of your program. Either rethrow it, or set the flag again with Thread.currentThread().interrupt() and stop working.
A complete example
This program classifies every outcome. It returns the body on success and throws a custom exception for everything else, so callers handle one failure type.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
public class SafeGet {
static class ApiException extends Exception {
final int status;
ApiException(String message, int status, Throwable cause) {
super(message, cause);
this.status = status;
}
}
static String fetch(HttpClient client, HttpRequest request) throws ApiException {
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 200 && status < 300) {
return response.body();
}
throw new ApiException("HTTP " + status + ": " + response.body(), status, null);
} catch (HttpTimeoutException e) {
throw new ApiException("Timed out: " + e.getMessage(), -1, e);
} catch (IOException e) {
throw new ApiException("I/O failure: " + e, -1, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ApiException("Interrupted", -1, e);
}
}
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/missing"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
try {
System.out.println(fetch(client, request));
} catch (ApiException e) {
System.err.println("Failed (status " + e.status + "): " + e.getMessage());
}
}
}The status -1 marks failures where no response existed. A caller can then tell "the server said 503" from "the network failed" by looking at one field.
Failures in sendAsync
sendAsync never throws these exceptions at the call site. It returns a CompletableFuture, and any failure completes that future exceptionally.
- In
exceptionallyorhandle, the exception is often wrapped in aCompletionException. CallgetCause()to reach theIOException. join()throws an uncheckedCompletionException.get()throws a checkedExecutionException. Both wrap the real cause.- A non-2xx status still completes the future normally. Check the status inside
thenApply, or throw there to push the failure down the exceptional path.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletionException;
public class AsyncFailures {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/missing")).build();
String result = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() >= 400) {
throw new IllegalStateException("HTTP " + response.statusCode());
}
return response.body();
})
.exceptionally(ex -> {
Throwable cause = (ex instanceof CompletionException && ex.getCause() != null)
? ex.getCause() : ex;
String kind = cause instanceof IOException ? "network" : "other";
return "failed (" + kind + "): " + cause;
})
.join();
System.out.println(result);
}
}An exception thrown inside thenApply is wrapped in a CompletionException by the time exceptionally sees it. The unwrapping line handles both wrapped and unwrapped cases.
Common mistakes
- Parsing the body before checking the status. A 500 page then fails in your JSON parser, and the real cause is lost.
- Catching
IOExceptionbeforeHttpTimeoutException. The second block becomes unreachable and the code does not compile. Reversing the order fixes it. - Ignoring
InterruptedException. An empty catch block makes the thread impossible to cancel cleanly. - Assuming a thrown exception means the server did nothing. If the read timeout fires after the request was sent, the server may have processed it. This matters for POST requests, because repeating them can create duplicates.
Exercise
A call to client.send(request, BodyHandlers.ofString()) returns normally, and response.statusCode() is 503. Did the code reach any catch block, and what should the caller do next?
Show answer
No catch block ran, because a 503 is a valid HTTP response and send only throws when no response arrives. The caller must check the status itself. A 503 is a server-side, often temporary failure, so it is a candidate for a retry with backoff, after logging the status and body.
Exercise
In sendAsync(...).thenApply(...).exceptionally(ex -> ...), a connection is refused. What type does ex usually have, and how do you get the underlying IOException?
Show answer
ex is usually a CompletionException, and ex.getCause() returns the underlying IOException, such as a ConnectException. Check for a null cause, because ex is sometimes already the unwrapped exception.