如果Http状态为500,SpringRESTTemplate将抛出always异常
是否可以在不使用异常的情况下使用SpringRESTTemplate来处理状态为500的http响应如果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
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注释