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

标签 spring

这个问题在这里已经有了答案:





Rest Template custom exception handling

(2 个回答)


4年前关闭。




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

最佳答案

您可以使用注释创建 Controller @ControllerAdvice如果您使用 springmvc。在 Controller 中写:

@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 在 Controller 建议中在异常发生时获取响应消息。

关于如果 Http 状态为 500,Spring RestTemplate 总是抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31728111/

相关文章:

java - 如何在 spring MVC 中 Autowiring 多级继承类

spring - Spring RESTful Web 服务的端口绑定(bind)

java - MyBatis+Redis 缓存。可能吗?

spring - 写入时保险库错误

java - HttpSecurity、WebSecurity 和 AuthenticationManagerBuilder

spring - Spring Batch 的问题

java - Spring Boot 可以将本地配置文件与同名的捆绑配置文件合并吗?

java - spring security第一次登录失败,第二次登录成功

Spring Boot 单页应用程序 - 将每个请求转发到 index.html

java - : SpringIocContainer | ApplicationContext | WebApplicationContext之间的关联