Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果Http状态为500,SpringRESTTemplate将抛出always异常_Spring - Fatal编程技术网

如果Http状态为500,SpringRESTTemplate将抛出always异常

如果Http状态为500,SpringRESTTemplate将抛出always异常,spring,Spring,是否可以在不使用异常的情况下使用SpringRESTTemplate来处理状态为500的http响应 RestTemplate restTemplate = new RestTemplate(); try { response = restTemplate.getForEntity(probe.getUrl(), String.class); boolean isOK = response.getStatusCode

是否可以在不使用异常的情况下使用SpringRESTTemplate来处理状态为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...
        }

未测试,但您可以简单地说它不是一个,或者它扩展了DefaultResponseErrorHandler,但覆盖了它。

如果您使用springmvc,您可以使用annotation
@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注释