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.
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
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