I am calling Restservice through RestTemplate and trying to override ResponseErrorHandler in Spring 3.2 to handle custom error codes.
CustomResponseErrroHandler
public class MyResponseErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { boolean hasError = false; int rawStatusCode = response.getRawStatusCode(); if (rawStatusCode != 200){ hasError = true; } return hasError; } @Override public void handleError(ClientHttpResponse response) throws IOException { //String body = IOUtils.toString(response.getBody()); throw new CustomServiceException(response.getRawStatusCode() , "custom Error"); } }
Spring framework invokes hasError method but not handleError, so I couldn't throw my customException. After delving into Spring RestTemplate source code, I realized the code in handleResponseError method is causing the issue - It is looking for response.getStatusCode or response.getStatusText and throwing exception (as statuscode/statustext is null when rest service throws exception) and it never calls either custom implemented or default handleError method in the next line
Spring RestTemplate Sourcecode for handleResponse:
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException { if (logger.isWarnEnabled()) { try { logger.warn(method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + "); invoking error handler"); } catch (IOException e) { // ignore } } getErrorHandler().handleError(response); }
FYI, While service throws exception, I can read rawstatuscode but not statuscode from response
How to bypass this framework code and make call my customhandler? Thanks for your help in advance.