Spring RestTemplate exchange POST HttpClientException with any non 200 OK response

The default behavior of RestTemplate on encountering error response codes is throwing an exception. In case of 4xx it's HttpClientErrorException and in case of 5xx: HttpServerErrorException (both extending HttpStatusCodeException). Spring achieves that by using ResponseErrorHandler (and it's default imlpementation - DefaultResponseErrorHandler)

One way of handling this would be to catch them:

try {
    ResponseEntity<String> response = restTemplate.exchange(fruitBasketUrl, HttpMethod.POST, fruit, String.class);
} catch(HttpClientErrorException e) {
    //handle 4xx errors
} catch(HttpServerErrorException e) {
    //handle 5xx errors
}

If you need to customize this behaviour (some rest API's use those codes when sending legitimate responses to some requests which you then may want to process as you do with 2xx response), you can create your own implementation of ResponseErrorHandler by implementing it or extending DefaultResponseHandler and then registering your handler with the RestTemplate during it's initialization:

public class MyResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        // check if response code is an error in here or just use default implementation
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        // handle different response codes
        // (default spring behaviour is throwing an exception)
    }
}

And registering:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
// now RestTemplate's behaviour for error status codes is customized

There's nothing wrong here. This exception will be thrown if you receive erroneous status code.

You just need to wrap your client side code in a try-catch and catch the exception and then do whatever you want to do with it.

try {
    ResponseEntity<String> response = restTemplate.exchange(fruitBasketUrl, HttpMethod.POST, fruit, String.class);
} catch (HttpStatusCodeException e) {
    e.getMessage();
}