Search code examples
javajerseyrequestjersey-2.0jersey-client

java jersey retry request on SocketTimeoutException


I have a Jersey client and want to implement retry upon SocketTimeoutException, which is the error I see on the server log. The code skeleton is below. webtarget is a javax.ws.rs.client.WebTarget instance with the url path and queryparams already defined. The issue I'm facing is that webtarget.request.get() never throws any SocketTimeoutException so I can't actually catch this exception. Any thoughts how I can actually implement the retry?

int i = 0;
Response response;
while (true) {
    try {
        response = webtarget.request().get();
        break;
    } catch (SocketTimeoutException e){
        if (i < retryNumber) {
            i++;
        } else {
            // throws some exception
        }
    }
}

Solution

  • I ended up figuring out the solution. It turns out the SocketTimeoutException is mapped into a ProcessingException that is actually thrown by the Jersey client. So the following code worked

    int i = 0;
    Response response;
    while (true) {
        try {
            response = webtarget.request().get();
            break;
        } catch (ProcessingException e){
            if (e.getCause() instanceof SocketTimeoutException && i < retryNumber) {
                i++;
            } else {
                // throws some exception
            }
        }
    }