Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:


November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:


1. Overview

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

2. Default Error Handling

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

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

All of these exceptions are extensions of RestClientResponseException.

Obviously, the simplest strategy to add custom error handling is to wrap the call in a try/catch block. Then we can 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 would be more efficient if we could implement a reusable error handler for all of our remote calls.

3. Implementing a ResponseErrorHandler

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.

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

So let's first implement our RestTemplateResponseErrorHandler:

public class RestTemplateResponseErrorHandler 
  implements ResponseErrorHandler {

    public boolean hasError(ClientHttpResponse httpResponse) 
      throws IOException {

        return (
          httpResponse.getStatusCode().series() == CLIENT_ERROR 
          || httpResponse.getStatusCode().series() == SERVER_ERROR);

    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();

Then we can build the RestTemplate instance using the RestTemplateBuilder to introduce our RestTemplateResponseErrorHandler:

public class BarConsumerService {

    private RestTemplate restTemplate;

    public BarConsumerService(RestTemplateBuilder restTemplateBuilder) {
        RestTemplate restTemplate = restTemplateBuilder
          .errorHandler(new RestTemplateResponseErrorHandler())

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


4. Testing Our Implementation

Finally, we'll test this handler by mocking a server and returning a NOT_FOUND status:

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

    private MockRestServiceServer server;
    private RestTemplateBuilder builder;

    public void  givenRemoteApiCall_when404Error_thenThrowNotFound() {

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

          .expect(ExpectedCount.once(), requestTo("/bars/4242"))

        Assertions.assertThrows(NotFoundException.class, () -> {
            Bar response = restTemplate.getForObject("/bars/4242", Bar.class);

5. Conclusion

In this article, we 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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:


HTTPClient footer
Inline Feedbacks
View all comments
Comments are closed on this article!