Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate throws always Exception if Http status is 500 [duplicate]

Tags:

spring

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

        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...
        }
like image 289
yogiginger Avatar asked Mar 15 '23 06:03

yogiginger


2 Answers

You can create a controller using annotation @ControllerAdvice if you using springmvc. In the controller write:

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

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

and the DefaultResponseErrorHandler throw these two kinds of exceptions:

@Override
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));
        default:
            throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}

and you can use:e.getResponseBodyAsString();e.getStatusCode(); blabla in the controller advice to get response message when the exceptions occurs.

like image 80
Qy Zuo Avatar answered Apr 28 '23 05:04

Qy Zuo


Not tested, but you could simply use a custom ResponseErrorHandler that is not a DefaultResponseErrorHandler, or that extends DefaultResponseErrorHandler but overrides hasError().

like image 33
JB Nizet Avatar answered Apr 28 '23 05:04

JB Nizet