title: Implementing the ResponseErrorHandler Interface
body: <p>I'm trying to override the ResponseErrorHandler interface to be able to return the entire request (status code, body etc.) in case of any response other than 2xx.</p>
  
  <p>I noticed that the Spring (RestTemplate) default returns an exception in case of a response other than 2xx. I do not want to return an exception, I just want to be able to return a:</p>
  
  <p><code>new ResponseEntity(HttpStatus.STATUS_CODE)</code></p>
  
  <p>Following some tutorials, I've found the following code:</p>
  
  <pre><code>@Component
  public class LoginErrorHandler
          implements ResponseErrorHandler {
  
      @Override
      public boolean hasError(ClientHttpResponse httpResponse)
              throws IOException {
  
          return (
                  httpResponse.getStatusCode().series() == CLIENT_ERROR
                          || httpResponse.getStatusCode().series() == SERVER_ERROR);
      }
  
      @Override
      public void handleError(ClientHttpResponse httpResponse)
              throws IOException {
          if (httpResponse.getStatusCode()
                  .series() == SERVER_ERROR) {
              // handle SERVER_ERROR
          } else if (httpResponse.getStatusCode()
                  .series() == CLIENT_ERROR) {
              // handle CLIENT_ERROR
          }
      }
  </code></pre>
  
  <p>(<a href="https://www.baeldung.com/spring-rest-template-error-handling" rel="nofollow noreferrer">Reference</a>)</p>
  
  <p>But I have not understood how I can return a ResponseEntity without changing the method return (which I can not by implementing the method).</p>
  
  <p>Implementation:</p>
  
  <pre><code>HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; request = new HttpEntity&lt;&gt;(map, headers);
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.setErrorHandler(new LoginErrorHandler());
  
  return restTemplate.postForEntity(url, request, String.class);
  </code></pre>