【问题标题】:Spring RestTemplate throws always Exception if Http status is 500 [duplicate]如果Http状态为500,Spring RestTemplate总是抛出异常[重复]
【发布时间】:2015-07-30 15:35:03
【问题描述】:

是否可以在不使用异常的情况下使用 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...
        }

【问题讨论】:

  • 如果没有catch,你将如何处理异常?你到底想实现什么?

标签: spring


【解决方案1】:

如果你使用 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 来获取异常发生时的响应消息。

【讨论】:

  • 这些配置应该属于哪一类?
  • @Mike.Chun 这应该在用ControllerAdvice注解的Controller类中
【解决方案2】:

未测试,但您可以简单地使用不是 DefaultResponseErrorHandleruse a custom ResponseErrorHandler,或者扩展 DefaultResponseErrorHandler 但覆盖 hasError()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2017-06-25
    • 2014-01-18
    • 2023-03-24
    • 2013-02-04
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多