Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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 our ResponseErrorHandler implementation into the RestTemplate instance. To do this, we use the RestTemplateBuilder to replace the default error handler in the response flow.

3.1. Handling Common HTTP Errors

Let’s first implement a simple RestTemplateResponseErrorHandler that handles common HTTP errors such as 4xx and 5xx statuses. For example, we handle 404 errors by throwing a custom NotFoundException:

@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
        return httpResponse.getStatusCode().is5xxServerError() || 
            httpResponse.getStatusCode().is4xxClientError();
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse) throws IOException {
        if (httpResponse.getStatusCode().is5xxServerError()) {
            //Handle SERVER_ERROR
            throw new HttpClientErrorException(httpResponse.getStatusCode());
        } else if (httpResponse.getStatusCode().is4xxClientError()) {
            //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:

@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);
    }

}

3.2. Handling 401 Unauthorized and Parsing the Response Body

Sometimes, when an API returns a 401 Unauthorized status, the response body includes useful details such as error messages that we may want to extract and use.

Since the ResponseErrorHandler.handleError() method does not automatically deserialize the response body, a common approach is to catch the HttpStatusCodeException thrown by RestTemplate and manually extract the body. To handle a 401 Unauthorized status more effectively, we can wrap the request in a try-catch block and inspect the response body when the exception is thrown:

public Bar fetchBarById(String barId) {
    try {
        return restTemplate.getForObject("/bars/" + barId, Bar.class);
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            String responseBody = e.getResponseBodyAsString();
            throw new UnauthorizedException("Unauthorized access: " + responseBody);
        }
        throw e;
    }
}

This approach allows us to handle 401 Unauthorized errors in a controlled and informative way. By catching the exception and manually extracting the response body, we can inspect any error details returned by the server, such as a message indicating why authentication failed or instructions for recovering from the issue. This gives us the flexibility to provide clearer feedback to the user, log more descriptive messages for troubleshooting, or even trigger fallback mechanisms depending on the contents of the response.

4. Testing Our Implementation

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

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

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

    @Test
    public void  givenRemoteApiCall_when404Error_thenThrowNotFound() {
        Assertions.assertNotNull(this.builder);
        Assertions.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));

        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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW