I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll discuss how to implement and inject the ResponseErrorHandler interface in a RestTemplate instance – to gracefully handle HTTP errors returned by remote APIs. 

2. Default Error Handling

By default, the RestTemplate will throw one of these exceptions in case of an HTTP error:

  1. HttpClientErrorException – in case of HTTP status 4xx
  2. HttpServerErrorException – in case of HTTP status 5xx
  3. UnknownHttpStatusCodeException – in case of an unknown HTTP status

All these exceptions are extensions of RestClientResponseException.

Obviously, the simplest strategy to add a custom error handling is to wrap the call in a try/catch block. Then, we process the caught exception as we see fit.

However, this simple strategy doesn’t scale well as the number of remote APIs or calls increases. It’d be more efficient if we could implement a reusable error handler for all of our remote calls.

3. Implementing a ResponseErrorHandler

And so, a class that implements ResponseErrorHandler will read the HTTP status from the response and either:

  1. Throw an exception that is meaningful to our application
  2. Simply ignore the HTTP status and let the response flow continue without interruption

We need to inject the ResponseErrorHandler implementation into the RestTemplate instance.

Hence, we use the RestTemplateBuilder to build the template and replace the DefaultResponseErrorHandler in the response flow.

So let’s first implement our RestTemplateResponseErrorHandler:

@Component
public class RestTemplateResponseErrorHandler 
  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() == HttpStatus.Series.SERVER_ERROR) {
            // handle SERVER_ERROR
        } else if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.CLIENT_ERROR) {
            // handle CLIENT_ERROR
            if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw new NotFoundException();
            }
        }
    }
}

Next, we build the RestTemplate instance using the RestTemplateBuilder to introduce our RestTemplateResponseErrorHandler:

@Service
public class BarConsumerService {

    private RestTemplate restTemplate;

    @Autowired
    public BarConsumerService(RestTemplateBuilder restTemplateBuilder) {
        RestTemplate restTemplate = restTemplateBuilder
          .errorHandler(new RestTemplateResponseErrorHandler())
          .build();
    }

    public Bar fetchBarById(String barId) {
        return restTemplate.getForObject("/bars/4242", Bar.class);
    }

}

4. Testing our Implementation

Finally, let’s test this handler by mocking a server and returning a NOT_FOUND status:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { NotFoundException.class, Bar.class })
@RestClientTest
public class RestTemplateResponseErrorHandlerIntegrationTest {

    @Autowired 
    private MockRestServiceServer server;
 
    @Autowired 
    private RestTemplateBuilder builder;

    @Test(expected = NotFoundException.class)
    public void  givenRemoteApiCall_when404Error_thenThrowNotFound() {
        Assert.assertNotNull(this.builder);
        Assert.assertNotNull(this.server);

        RestTemplate restTemplate = this.builder
          .errorHandler(new RestTemplateResponseErrorHandler())
          .build();

        this.server
          .expect(ExpectedCount.once(), requestTo("/bars/4242"))
          .andExpect(method(HttpMethod.GET))
          .andRespond(withStatus(HttpStatus.NOT_FOUND));

        Bar response = restTemplate 
          .getForObject("/bars/4242", Bar.class);
        this.server.verify();
    }
}

5. Conclusion

This article presented a solution to implement and test a custom error handler for a RestTemplate that converts HTTP errors into meaningful exceptions.

As always, the code presented in this article is available over on Github.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Federico
Guest
Federico

I tried your code but the test fails because RestTemplate.doExecute catches IOExceptions and throws a ResourceAccessException so the expected exception is not met.
What did I do wrong?

Loredana Crusoveanu
Editor

Hey Federico,

Are you running the test in our codebase or your own? I’m able to run the RestTemplateResponseErrorHandlerIntegrationTest in the spring-rest-simple successfully.

You may need to adapt the example to your needs. In our case, the NotFoundException is thrown only for NOT_FOUND status:
if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new NotFoundException();
}

Federico
Guest
Federico

Hi Loredana, thanks for getting back to me. Obviously I have my codebase. I started the test in debug and the NotFoundException is correctly thrown by RestTemplateResponseErrorHandler but then the control comes back to RestTemplate.doExecute that catches the exception and throws a new ResourceAccessException that makes the test fail. This is the code from Spring RestTemplate class: /** * Execute the given method on the provided URI. * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback}; * the response with the {@link ResponseExtractor}. ... */ @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T>… Read more »

Loredana Crusoveanu
Editor

Ok, I see doExecute() catches an IOException, which NotFoundException is not. So my guess is the operation is throwing another exception after NotFoundException which the error handler isn’t dealing with. It’s difficult to say without seeing your project. If you want, you can create a PR against the project on GitHub that reproduces the issue and we’ll have a look.

Cheers.

Federico
Guest
Federico

NotFoundException must extend IOEXception, If not, it could not be used in
public void handleError(ClientHttpResponse httpResponse) throws IOException {...}
unless it extends an unchecked exception like RuntimeException

You should include the NotFoundException` class code in this page.

Loredana Crusoveanu
Editor