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 {

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

    @Override
    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

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...