Spring RestTemplate always throws exception if Http status is 500

Is it possible to use Spring RestTemplate without using Exceptions to handle HTTP response with 500 status?

        RestTemplate restTemplate = new RestTemplate();
        try {
            response = restTemplate.getForEntity(probe.getUrl(), String.class);
            boolean isOK = response.getStatusCode() == HttpStatus.OK;
            // would be nice if 500 would also stay here
        catch (HttpServerErrorException exc) {
            // but seems only possible to handle here...



source to share

2 answers

You can create a controller using annotation @ControllerAdvice

if you are using springmvc. In the controller, write:

public String handleXXException(HttpClientErrorException e) {
    log.error("log HttpClientErrorException: ", e);
    return "HttpClientErrorException_message";

public String handleXXException(HttpServerErrorException e) {
    log.error("log HttpServerErrorException: ", e);
    return "HttpServerErrorException_message";
// catch unknown error
public String handleException(Exception e) {
    log.error("log unknown error", e);
    return "unknown_error_message";


and DefaultResponseErrorHandler

throw these two kinds of exceptions:

public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = getHttpStatusCode(response);
    switch (statusCode.series()) {
        case CLIENT_ERROR:
            throw new HttpClientErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
        case SERVER_ERROR:
            throw new HttpServerErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
            throw new RestClientException("Unknown status code [" + statusCode + "]");


and you can use: e.getResponseBodyAsString();

, e.getStatusCode();

blabla in the controller board to receive a reply message when exceptions occur.



Untested, but you can just use a customResponseErrorHandler

one that is not DefaultResponseErrorHandler

or extends DefaultResponseErrorHandler but overrides hasError()




All Articles