Considering the case when a call to a web service with Spring RestTemplate return an error response and we want to handle this error as a Java object.
RestTemplate error responses can be handled implementing the class ResponseErrorHandler.
Considering a JSON response error like the following lets see how to transform it in a

    "errorCode": "1",
    "errorMessage": "Something goes wrong"

This is the POJO that represent the error response:

public class ErrorResponse {
    private String errorCode;
    private String errorMessage;


And this is a custom exception.

public class CustomException extends RuntimeException {
    private String errorCode;
    private String errorMessage;

Below the implementation of ResponseErrorHandler interface where we can handle the error response and convert it in our POJO using HttpMessageConverterExtractor.
After we have the response as POJO we can us it for example to throw an exception passing the error data.

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpMessageConverterExtractor;
import org.springframework.web.client.ResponseErrorHandler;

import java.util.Arrays;
import java.util.List;

public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {

    private List<HttpMessageConverter<?>> messageConverters = Arrays.asList(new MappingJackson2HttpMessageConverter());

    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        return (clientHttpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR
                || clientHttpResponse.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR);

    public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
        HttpMessageConverterExtractor<ErrorResponse> errorMessageExtractor =
                new HttpMessageConverterExtractor(ErrorResponse.class, messageConverters);

        try {
            ErrorResponse errorResponse = errorMessageExtractor.extractData(clientHttpResponse);
            throw new CustomException(errorResponse.getErrorCode(), errorResponse.getErrorMessage());
        } catch (IOException e) {
            // ...

RestTemplateResponseErrorHandler can be set to the RestTemplate like below:

RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler(clientErrorResponseHandler));