Exception handling with RestTemplate

Spring framework offers RestTemplate for consuming RESTful services. Recently I used RestTemplate for consuming one of the third party RESTful service.

RestTemplate offers 'ResponseErrorHandler'; which you can extend to decide which are errors for you and how to handle those error. You can override hasError and handleError methods of ResponseErrorHandler.
In handleError you can throw customException if you want, as outlined in below code.

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

public class RestTemplateErrorHandler implements ResponseErrorHandler {

    public void handleError(ClientHttpResponse response) throws IOException
        throw new MyCustomException(response.getStatusText(), response.getStatusCode());

    public boolean hasError(ClientHttpResponse response) throws IOException
        if ( (response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR)
                || (response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR))
            return true;
        return false;

But there is caveat with this error handler. If the server is down or not accessible, RestTemplate throws 'ResourceAccessException'. Internally RestTemplate encounters 'IOException' when server is not accessible. RestTemplate catches 'IOException' and throws 'ResourceAccessException'. In this process error handler doesn't  get invoked hence the custom exception will not be thrown.

So to avoid this situation I handled 'RestClientException' in code where RestTemplate was being invoked, and returned proper error message.

Related Posts:
Exception handeling for RESTful service


Popular posts from this blog

MSMQ error : "A workgroup installation computer does not support the operation."

How to flash CWM Recovery to Samsung Galaxy SL( GT-I9003) using Odin

Error : login failed on rabbitmq web-management console