如果Http状态为500,Spring RestTemplate将始终抛出异常

时间:2015-07-30 15:35:03

标签: spring

是否可以使用Spring RestTemplate而不使用Exceptions来处理状态为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...
        }

2 个答案:

答案 0 :(得分:4)

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

@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";
}

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 + "]");
    }
}

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

答案 1 :(得分:2)

未经测试,但您可能只是use a custom ResponseErrorHandler,而不是DefaultResponseErrorHandler,或者扩展了DefaultResponseErrorHandler,但会覆盖hasError()