如果 Http 状态为 500,Spring RestTemplate 总是抛出异常

yog*_*ger 4 spring

是否可以在不使用异常的情况下使用 Spring RestTemplate 来处理状态为 500 的 http 响应?

        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...
        }
Run Code Online (Sandbox Code Playgroud)

Qy *_*Zuo 5

@ControllerAdvice如果使用 springmvc,则可以使用注释创建控制器。在控制器中写:

@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";
}
Run Code Online (Sandbox Code Playgroud)

DefaultResponseErrorHandler抛出这两种异常:

@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 + "]");
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以使用:e.getResponseBodyAsString();e.getStatusCode();blabla 在控制器建议中在异常发生时获取响应消息。