title: Spring RestTemplate - Overriding ResponseErrorHandler
body: <p>I am calling a <code>ReST</code> service through <code>RestTemplate</code> and trying to override <code>ResponseErrorHandler</code> in <code>Spring 3.2</code> to handle custom error codes.</p>
  
  <p><strong>CustomResponseErrroHandler</strong></p>
  
  <pre><code>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");
     }
  }
  </code></pre>
  
  <p><code>Spring</code> framework invokes <code>hasError</code> method but not <code>handleError</code>, so I couldn't throw my custom exception. After delving into <code>Spring</code> <code>RestTemplate</code> source code, I realized that the code in <code>handleResponseError</code> method is causing the issue - It is looking for <code>response.getStatusCode</code> or <code>response.getStatusText</code> and throwing exception (as statusCode/statusText is null when <code>Rest</code> service throws exception) and it never calls either custom implemented or default <code>handleError</code> method in the next line.</p>
  
  <p><code>Spring</code> <code>RestTemplate</code> source code for <code>handleResponse</code> method:</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>FYI, while service throws exception, I can read rawstatuscode but not statuscode from response</p>
  
  <p>How to bypass this framework code and make call  my custom handler?
  Thanks for your help in advance.</p>