Skip to lesson

Handling network failures

When the ShopLite API is down, your app gets no answer at all, not even an error status. A robust client names each failure for the user and retries only when a second try cannot do harm.

What can fail on the way

A network failure is any problem that stops a complete HTTP response from reaching your program. In HttpClient, send reports it by throwing an IOException or one of its subclasses.

A call can fail in several places: unknown host, refused connection, no answer, a TLS error, a slow server or a reset connection. Each one needs a different reaction.

Four places where a call can go wrong. First, opening the connection: an unknown host or refused connection gives ConnectException, and the connect timeout gives HttpConnectTimeoutException. Second, waiting for the answer: the request timeout gives HttpTimeoutException.

Example 1 · Five ways a call can fail

FailureTourDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;
public class FailureTourDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder()            .connectTimeout(Duration.ofSeconds(3))            .build();
    static void tryCall(String label, String scheme, String address) throws InterruptedException {        HttpRequest request = HttpRequest.newBuilder(URI.create(scheme + "://" + address)).timeout(Duration.ofSeconds(3)).build();        try {            int status = CLIENT.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();            System.out.println(label + " -> status " + status);        } catch (IOException e) {            Throwable root = e;            while (root.getCause() != null && root.getCause() != root) {                root = root.getCause();                               // walk down to the first cause            }            System.out.println(label + " -> " + e.getClass().getName() + ": " + e.getMessage());            if (root != e) {                System.out.println("      root cause: " + root);            }        }    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        slow.createContext("/", exchange -> {            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }            exchange.sendResponseHeaders(204, -1);            exchange.close();        });        slow.start();        int port = slow.getAddress().getPort();        try {            tryCall("1. Unknown host     ", "http", "shoplite.invalid/api/v1/products");            tryCall("2. Nothing listening", "http", "127.0.0.1:1/api/v1/products");            tryCall("3. No answer at all ", "http", "10.255.255.1/api/v1/products");            tryCall("4. Bad certificate  ", "https", "self-signed.badssl.com/");            tryCall("5. Slow server      ", "http", "127.0.0.1:" + port + "/api/v1/products");        } finally {            slow.stop(0);        }    }}
Sample output
1. Unknown host      -> java.net.ConnectException: null
      root cause: java.nio.channels.UnresolvedAddressException
2. Nothing listening -> java.net.ConnectException: null
      root cause: java.nio.channels.ClosedChannelException
3. No answer at all  -> java.net.http.HttpConnectTimeoutException: HTTP connect timed out
      root cause: java.net.ConnectException: HTTP connect timed out
4. Bad certificate   -> javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      root cause: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
5. Slow server       -> java.net.http.HttpTimeoutException: request timed out

What this code does

  • Cases 1 and 2 are both ConnectException with a null message; only the root cause (UnresolvedAddressException or ClosedChannelException) tells them apart.
  • Case 3 waits the full 3 s connect timeout, case 4 is a real TLS error from a site with a self-signed certificate, and case 5 is the 3 s request timeout against a server that needs 5 s.
  • The output depends on your network (some routers refuse case 3 at once), and case 4 needs internet, so treat it as a sample.

A typo in the host will never fix itself, a busy server may answer in a second, and a certificate error must never be "fixed" by turning off checks. The JDK often gives poor messages: an unknown host and a refused connection are both a ConnectException whose getMessage() is null. The real reason sits deeper in the chain of causes, so your code must add the context itself: which call, which host, what to check. The user deserves "the payment service is not reachable", not java.net.ConnectException: null.

The common failures:

  • unknown host name: a typo, or DNS is down.
  • connection refused: nothing runs on that port.
  • no answer at all: a firewall drops the packets, so only the connect timeout ends the wait.
  • TLS error: the HTTPS certificate is expired, self-signed or for another name.
  • slow server: the request timeout runs out.
  • connection reset halfway through the response.
A certificate error such as PKIX path building failed means the client cannot trust the server. Never "fix" it by trusting all certificates: that removes the protection HTTPS exists for. Fix the server certificate, or add the right CA to the trust store.

The exceptions behind the failures

ConnectException is the exception thrown when a connection cannot be made: the host name is unknown, the connection is refused or the network is unreachable. Its getMessage() is often null.

send throws IOException or a subclass for every network failure. Catch the most specific type first: HttpConnectTimeoutException, HttpTimeoutException, ConnectException, then IOException.

Example 2 · Catch the most specific failure first

CatchOrderDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.ConnectException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpConnectTimeoutException;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.net.http.HttpTimeoutException;import java.time.Duration;
public class CatchOrderDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
    /** Turns each kind of failure into one clear sentence. Most specific catch first. */    static String fetch(URI uri) throws InterruptedException {        HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(400)).build();        try {            return "status " + CLIENT.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();        } catch (HttpConnectTimeoutException e) {            return "server did not accept the connection in time";        } catch (HttpTimeoutException e) {            return "server accepted the call but did not answer in time";        } catch (ConnectException e) {            return "cannot connect to " + uri.getHost() + ":" + uri.getPort()                    + " (getMessage() is " + e.getMessage() + ")";        } catch (IOException e) {            return "network error: " + e;        }        // InterruptedException is not caught here: it goes up to the caller (next section)    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/reports", exchange -> {            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }            exchange.sendResponseHeaders(204, -1);            exchange.close();        });        server.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort();        try {            System.out.println("Slow report: " + fetch(URI.create(base + "/api/v1/reports")));        } finally {            server.stop(0);        }        System.out.println("Server gone: " + fetch(URI.create("http://127.0.0.1:1/api/v1/products")));    }}
Output
Slow report: server accepted the call but did not answer in time
Server gone: cannot connect to 127.0.0.1:1 (getMessage() is null)

What this code does

  • The catch blocks go from the most specific type to IOException, and each gives its own sentence. Swapping the two timeout blocks would not compile.
  • The refused connection shows why your own message matters: getMessage() is null, so the method names the host and port itself.
  • InterruptedException is not caught here; fetch declares it and lets it pass up, which is one of the correct choices.

HttpTimeoutException means the request timeout ran out, and its subclass HttpConnectTimeoutException means the connect timeout did. SSLHandshakeException (from javax.net.ssl) means TLS failed. InterruptedException is not a network failure at all: another thread asked this one to stop while it waited.

The reverse catch order does not compile, because a parent catch would already handle the child (exception HttpTimeoutException has already been caught). Use the type to choose your reaction and your message: timeouts and refused connections are often temporary, while a bad host name or a certificate problem needs a person to fix a setting.

Restoring the interrupt flag; never swallowing exceptions

The interrupt flag is a thread's polite request to stop. A thread waiting in send notices it and throws InterruptedException, which clears the flag; Thread.currentThread().interrupt() sets it again.

When you catch InterruptedException, set the flag again and stop the work by throwing your own exception. Never swallow an exception: catching it and carrying on as if nothing happened.

Example 3 · Cancel a slow call and keep the interrupt flag

InterruptDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;
/** Thrown when a call could not finish; the cause is kept. */class ApiCallException extends RuntimeException {    ApiCallException(String message, Throwable cause) {        super(message, cause);    }}
public class InterruptDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
    static int stockOf(URI uri) {        HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(5)).build();        try {            return CLIENT.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();                          // 1. put the flag back            throw new ApiCallException("Stock call was cancelled", e);   // 2. never swallow: tell the caller        } catch (IOException e) {            throw new ApiCallException("Stock call failed: " + e, e);        }    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products/1/stock", exchange -> {            try {                Thread.sleep(1500);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }            exchange.sendResponseHeaders(204, -1);            exchange.close();        });        server.start();        URI stock = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/1/stock");
        Thread worker = new Thread(() -> {            try {                System.out.println("worker: status " + stockOf(stock));            } catch (ApiCallException e) {                System.out.println("worker: " + e.getMessage() + " (cause " + e.getCause().getClass().getSimpleName() + ")");                System.out.println("worker: interrupted flag is " + Thread.currentThread().isInterrupted());            }        });        worker.start();        Thread.sleep(300);        System.out.println("main: user pressed Cancel, interrupting the worker");        worker.interrupt();        worker.join();        server.stop(0);    }}
Output
main: user pressed Cancel, interrupting the worker
worker: Stock call was cancelled (cause InterruptedException)
worker: interrupted flag is true

What this code does

  • The worker waits in send; worker.interrupt() makes send throw InterruptedException at once instead of waiting 1.5 s.
  • The catch restores the flag with Thread.currentThread().interrupt() and throws ApiCallException with the original as its cause, so the worker can see it was cancelled.

Code higher up, such as a thread pool shutting down, depends on seeing the interrupt flag. Swallowing, such as catch (Exception e) { return -1; } or an empty catch, makes the program show wrong data (attendance -1%), retry forever or ignore a user's Cancel, and the logs have no clue why. Every catch must do one of three things: handle the problem for real (a fallback the user is told about), add context and rethrow, or let the exception pass up.

When you wrap an exception, always pass the original as the cause (new ApiCallException(message, e)), so the full chain appears in the stack trace.

Retrying only idempotent requests, with backoff and a limit

An idempotent request has the same effect when sent twice as when sent once, such as GET, PUT and DELETE. A POST is not idempotent, so a blind retry can create a second order.

Retry only idempotent requests, only after temporary failures (a timeout, a refused connection, a 503), with a limit on attempts and a longer wait each time.

Example 4 · Retry a GET with exponential backoff and a limit

RetryDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.ConnectException;import java.net.InetSocketAddress;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.nio.charset.StandardCharsets;import java.time.Duration;import java.util.Set;import java.util.concurrent.atomic.AtomicInteger;
public class RetryDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();    private static final Set<String> IDEMPOTENT = Set.of("GET", "HEAD", "PUT", "DELETE");    private static final Set<Integer> RETRYABLE = Set.of(429, 502, 503, 504);
    /** Retries idempotent requests on timeouts, refused connections and 429/502/503/504. */    static HttpResponse<String> sendWithRetry(HttpRequest request, int maxAttempts)            throws IOException, InterruptedException {        if (!IDEMPOTENT.contains(request.method())) {            return CLIENT.send(request, HttpResponse.BodyHandlers.ofString());   // POST, PATCH: one try only        }        long delayMs = 100;        for (int attempt = 1; ; attempt++) {            try {                HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());                if (!RETRYABLE.contains(response.statusCode()) || attempt == maxAttempts) {                    return response;                }                System.out.println("  attempt " + attempt + ": " + response.statusCode() + ", wait " + delayMs + " ms");            } catch (HttpTimeoutException | ConnectException e) {                if (attempt == maxAttempts) {                    throw e;                                              // give up: the caller decides                }                System.out.println("  attempt " + attempt + ": " + e.getClass().getSimpleName() + ", wait " + delayMs + " ms");            }            Thread.sleep(delayMs);            delayMs *= 2;        }    }
    public static void main(String[] args) throws IOException, InterruptedException {        AtomicInteger calls = new AtomicInteger();        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products/1", exchange -> {            boolean warm = calls.incrementAndGet() > 2;            byte[] body = (warm ? "{\"id\":1,\"stock\":40}" : "busy").getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(warm ? 200 : 503, body.length);            exchange.getResponseBody().write(body);            exchange.close();        });        server.start();        URI product = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/1");        try {            HttpRequest get = HttpRequest.newBuilder(product).timeout(Duration.ofSeconds(2)).build();            System.out.println("GET with up to 4 attempts:");            HttpResponse<String> response = sendWithRetry(get, 4);            System.out.println("  final: " + response.statusCode() + " " + response.body());
            calls.set(0);            System.out.println("Same server, only 2 attempts:");            System.out.println("  final: " + sendWithRetry(get, 2).statusCode());        } finally {            server.stop(0);        }    }}
Output
GET with up to 4 attempts:
  attempt 1: 503, wait 100 ms
  attempt 2: 503, wait 200 ms
  final: 200 {"id":1,"stock":40}
Same server, only 2 attempts:
  attempt 1: 503, wait 100 ms
  final: 503

What this code does

  • sendWithRetry retries only methods in IDEMPOTENT, only for timeouts, refused connections and 429/502/503/504, and doubles the wait each time.
  • With 4 attempts the third call succeeds. With only 2 attempts the client stops and returns the last 503, so the caller still decides what to show.

Example 5 · Why a blind POST retry duplicates orders

DuplicateOrderDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;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;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;
/** An order API that saves each order at once, but answers the very first request slowly. */class OrderApi {    final AtomicInteger ordersSaved = new AtomicInteger();    private final AtomicInteger requests = new AtomicInteger();    private final Map<String, Integer> orderByKey = new ConcurrentHashMap<>();    private final ExecutorService threads = Executors.newFixedThreadPool(4);    private HttpServer server;
    URI start() throws IOException {        server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.setExecutor(threads);                                      // several requests at the same time        server.createContext("/api/v1/orders", exchange -> {            exchange.getRequestBody().readAllBytes();            String key = exchange.getRequestHeaders().getFirst("Idempotency-Key");            int id = key == null                    ? ordersSaved.incrementAndGet()                                    // always a new order                    : orderByKey.computeIfAbsent(key, k -> ordersSaved.incrementAndGet());            if (requests.incrementAndGet() == 1) {                pause(1500);            }            exchange.getResponseHeaders().set("Location", "/api/v1/orders/" + id);            exchange.sendResponseHeaders(201, -1);            exchange.close();        });        server.start();        return URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/orders");    }
    static void pause(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    void stop() {        server.stop(0);        threads.shutdown();    }}
public class DuplicateOrderDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();    private static final String ORDER = "{\"customerId\":1,\"addressId\":1,\"items\":[{\"productId\":6,\"quantity\":1}]}";
    /** Sends the POST; on a timeout, sends the same request once more. */    static void placeWithOneRetry(HttpRequest post) throws IOException, InterruptedException {        for (int attempt = 1; attempt <= 2; attempt++) {            try {                HttpResponse<Void> r = CLIENT.send(post, HttpResponse.BodyHandlers.discarding());                System.out.println("  attempt " + attempt + ": " + r.statusCode() + " " + r.headers().firstValue("Location").orElse(""));                return;            } catch (HttpTimeoutException e) {                System.out.println("  attempt " + attempt + ": timed out, sending again");            }        }    }
    static HttpRequest.Builder orderRequest(URI orders) {        return HttpRequest.newBuilder(orders)                .header("Content-Type", "application/json")                .timeout(Duration.ofMillis(600))                .POST(HttpRequest.BodyPublishers.ofString(ORDER));    }
    public static void main(String[] args) throws IOException, InterruptedException {        OrderApi blind = new OrderApi();        URI orders = blind.start();        System.out.println("Blind retry of a POST:");        placeWithOneRetry(orderRequest(orders).build());        blind.stop();        System.out.println("  orders saved on the server: " + blind.ordersSaved.get());
        OrderApi safe = new OrderApi();        orders = safe.start();        System.out.println("Retry with an Idempotency-Key:");        placeWithOneRetry(orderRequest(orders)                .header("Idempotency-Key", "order-7f3a9c")                .build());        safe.stop();        System.out.println("  orders saved on the server: " + safe.ordersSaved.get());    }}
Output
Blind retry of a POST:
  attempt 1: timed out, sending again
  attempt 2: 201 /api/v1/orders/2
  orders saved on the server: 2
Retry with an Idempotency-Key:
  attempt 1: timed out, sending again
  attempt 2: 201 /api/v1/orders/1
  orders saved on the server: 1

What this code does

  • The server saves the order and only then answers slowly. The client times out, does not know the order exists, and sends it again: two orders for one click.
  • With the same Idempotency-Key on both attempts, the server returns the first order (/api/v1/orders/1) for the retry, so only one order is saved.
  • The key is made once per order (a fixed text here; usually a UUID), not once per attempt.

Never retry 4xx errors such as 400 or 404: the same request gets the same answer. A POST that timed out may already have created the order, so retrying it can charge the customer twice. Exponential backoff doubles the wait (100 ms, 200 ms, 400 ms) so a struggling server gets room to recover; busy systems add jitter, a small random part of the wait, so thousands of clients do not retry at the same moment. When the server sends Retry-After, wait that long.

To make a POST safe to retry, send an Idempotency-Key header with a unique value per logical action (one per order, reused on every retry). A server that supports it saves the first result for that key and returns it again instead of creating a second order. UPI and card payment APIs work this way.

Order of execution

Order one retry round

Put the steps of a GET retry loop in the order they happen.

A clear exception type for callers

Give callers one exception type, such as ShopApiException, with a kind (unreachable, timeout, server error, rejected, cancelled), a clear message and the original exception as the cause.

Example 6 · One exception type with a kind and a clear message

ClearErrorsDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.ConnectException;import java.net.InetSocketAddress;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.nio.charset.StandardCharsets;import java.time.Duration;
/** The only exception callers of ShopApi need to know. */class ShopApiException extends RuntimeException {    enum Kind { UNREACHABLE, TIMEOUT, SERVER_ERROR, REJECTED, CANCELLED }
    private final Kind kind;
    ShopApiException(Kind kind, String message, Throwable cause) {        super(message, cause);        this.kind = kind;    }
    Kind kind() {        return kind;    }
    /** Worth trying again later? */    boolean isTemporary() {        return kind == Kind.UNREACHABLE || kind == Kind.TIMEOUT || kind == Kind.SERVER_ERROR;    }}
class Pause {    static void sleep(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
class ShopApi {    private static final Duration TIMEOUT = Duration.ofMillis(1500);
    private final HttpClient http;    private final URI baseUrl;
    ShopApi(HttpClient http, URI baseUrl) {        this.http = http;        this.baseUrl = baseUrl;    }
    String get(String path) {        HttpRequest request = HttpRequest.newBuilder(baseUrl.resolve(path)).timeout(TIMEOUT).build();        String call = "GET " + path;        try {            HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());            int status = response.statusCode();            if (status >= 500) {                throw new ShopApiException(ShopApiException.Kind.SERVER_ERROR, call + " failed: server error " + status, null);            }            if (status >= 400) {                throw new ShopApiException(ShopApiException.Kind.REJECTED, call + " was rejected with " + status, null);            }            return response.body();        } catch (HttpTimeoutException e) {            throw new ShopApiException(ShopApiException.Kind.TIMEOUT, call + " failed: no answer within " + TIMEOUT.toMillis() + " ms", e);        } catch (ConnectException e) {            throw new ShopApiException(ShopApiException.Kind.UNREACHABLE, call + " failed: cannot connect to "                    + baseUrl.getHost() + ":" + baseUrl.getPort() + " (is the ShopLite API running?)", e);        } catch (IOException e) {            throw new ShopApiException(ShopApiException.Kind.UNREACHABLE, call + " failed: " + e, e);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new ShopApiException(ShopApiException.Kind.CANCELLED, call + " was cancelled", e);        }    }}
public class ClearErrorsDemo {    static void show(ShopApi api, String path) {        try {            System.out.println("OK   " + api.get(path));        } catch (ShopApiException e) {            System.out.println(e.kind() + (e.isTemporary() ? " (temporary)" : "") + ": " + e.getMessage());        }    }
    public static void main(String[] args) throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/", exchange -> {            String path = exchange.getRequestURI().getPath();            int status = path.endsWith("/1") ? 200 : path.endsWith("/5") ? 503 : 404;            if (path.contains("reports")) {                Pause.sleep(2500);                                  // a slow report                status = 200;            }            byte[] body = "{\"id\":1}".getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(status, body.length);            exchange.getResponseBody().write(body);            exchange.close();        });        server.start();        HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();        ShopApi api = new ShopApi(http, URI.create("http://127.0.0.1:" + server.getAddress().getPort()));        try {            show(api, "/api/v1/products/1");            show(api, "/api/v1/products/99");            show(api, "/api/v1/products/5");            show(api, "/api/v1/reports/daily");        } finally {            server.stop(0);        }        show(new ShopApi(http, URI.create("http://127.0.0.1:1")), "/api/v1/products/1");    }}
Output
OK   {"id":1}
REJECTED: GET /api/v1/products/99 was rejected with 404
SERVER_ERROR (temporary): GET /api/v1/products/5 failed: server error 503
TIMEOUT (temporary): GET /api/v1/reports/daily failed: no answer within 1500 ms
UNREACHABLE (temporary): GET /api/v1/products/1 failed: cannot connect to 127.0.0.1:1 (is the ShopLite API running?)

What this code does

  • ShopApi.get turns every outcome into either a body or a ShopApiException with a Kind, a message that names the call, and the original cause.
  • The caller has one catch and uses isTemporary() to decide between "try again later" and "fix something". The refused connection even suggests what to check.
  • InterruptedException is also handled correctly: the flag is restored and the kind is CANCELLED.

The screen code then has one catch, and it can decide simply: show "try again later" when isTemporary() is true, or "contact support" otherwise. Messages like GET /api/v1/products/1 failed: cannot connect to 127.0.0.1:8080 (is the ShopLite API running?) save hours when someone reads the logs.

Good messages name the method and path, the host, the timeout used and the attempt count. They never contain passwords, tokens or full request bodies with personal data, because logs are read by many people.

Next step

Check your understanding

12 quick questions