springrestexceptionresttemplate

Spring RestTemplate exception handling


Below is the code snippet. Basically, I am trying to propagate the exception when the error code is anything other than 200.

ResponseEntity<Object> response = restTemplate.exchange(
    url.toString().replace("{version}", version), 
    HttpMethod.POST, 
    entity, 
    Object.class
);

if (response.getStatusCode().value() != 200) {
    logger.debug("Encountered Error while Calling API");
    throw new ApplicationException();
}

However, in the case of a 500 response from the server I am getting the exception

org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]

Do I really need to wrap the rest template exchange method in try? What would then be the purpose of codes?


Solution

  • You want to create a class that implements ResponseErrorHandler and then use an instance of it to set the error handling of your rest template:

    public class MyErrorHandler implements ResponseErrorHandler {
      @Override
      public void handleError(ClientHttpResponse response) throws IOException {
        // your error handling here
      }
    
      @Override
      public boolean hasError(ClientHttpResponse response) throws IOException {
         ...
      }
    }
    
    [...]
    
    public static void main(String args[]) {
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.setErrorHandler(new MyErrorHandler());
    }
    

    Also, Spring has the class DefaultResponseErrorHandler, which you can extend instead of implementing the interface, in case you only want to override the handleError method.

    public class MyErrorHandler extends DefaultResponseErrorHandler {
      @Override
      public void handleError(ClientHttpResponse response) throws IOException {
        // your error handling here
      }
    }
    

    Take a look at its source code to have an idea of how Spring handles HTTP errors.