CloseableHttpClient: will all exceptions go to retyHandler() if there's one?

3.6k views Asked by At

so i'm following this example for retryHandler(), it has the try/finally. My question is: how to do retry for exception ?

public class HttpClientRetryHandlerExample {

    public static void main(String... args) throws IOException {

        CloseableHttpClient httpclient = HttpClients.custom()
                .setRetryHandler(retryHandler())
                .build();

        try {
            HttpGet httpget = new HttpGet("http://localhost:1234");
            System.out.println("Executing request " + httpget.getRequestLine());
            httpclient.execute(httpget);
            System.out.println("----------------------------------------");
            System.out.println("Request finished");
        } finally {
            httpclient.close();
        }
    }

    private static HttpRequestRetryHandler retryHandler(){
        return (exception, executionCount, context) -> {

            System.out.println("try request: " + executionCount);

            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        };
    }
}

The question is, why the example just have try/finally without catch ? Does that mean all exceptions will go to retryHandler() ?

1

There are 1 answers

6
ok2c On
  1. The exception logic is implemented by HttpClient inside the request execution pipeline. HttpRequestRetryHandler is merely a decision strategy used to determine whether or not failed requests would be re-executed. I admit HttpRequestRetryHandler might be a misnomer. It is not actually a handler.

  2. Only I/O exceptions are considered recoverable. Runtime exceptions are propagated to the caller.