Spring Rest客户端异常处理
Spring Rest Client Exception Handling
我正在使用 spring RestTemplate
来消费休息服务(暴露在 spring 休息中)。我能够消费成功场景。但对于负面情况,服务 returns 错误消息和错误代码。我需要在我的网页中显示这些错误消息。
例如对于无效请求,服务会抛出 HttpStatus.BAD_REQUEST
并显示正确的消息。如果我放置 try-catch 块,它会转到 catch 块,我无法获得 ResponseEntity
对象。
try {
ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
});
responseEntity.getStatusCode();
} catch (Exception e) {
//TODO How to get response here, so that i can get error messages?
e.printStackTrace();
}
异常情况如何得到ResponseWrapper
?
我从 here 那里了解到 CustomRestTemplate
和 ResponseExtractor
,但无法决定哪一个最适合我的情况。
我找到了解决方案。 HttpClientErrorException
对我有用。
它有 e.getResponseBodyAsString()
函数,returns ResponseBody。
您可能想要区分:
HttpClientErrorException
(HTTP-状态 >=400)或 HttpServerErrorException
(HTTP-状态 >=500)甚至 RestClientException
.
此外,还有一个关于定义您自己的 ErrorHandler 的好文档,see this link
我正在使用 spring RestTemplate
来消费休息服务(暴露在 spring 休息中)。我能够消费成功场景。但对于负面情况,服务 returns 错误消息和错误代码。我需要在我的网页中显示这些错误消息。
例如对于无效请求,服务会抛出 HttpStatus.BAD_REQUEST
并显示正确的消息。如果我放置 try-catch 块,它会转到 catch 块,我无法获得 ResponseEntity
对象。
try {
ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
});
responseEntity.getStatusCode();
} catch (Exception e) {
//TODO How to get response here, so that i can get error messages?
e.printStackTrace();
}
异常情况如何得到ResponseWrapper
?
我从 here 那里了解到 CustomRestTemplate
和 ResponseExtractor
,但无法决定哪一个最适合我的情况。
我找到了解决方案。 HttpClientErrorException
对我有用。
它有 e.getResponseBodyAsString()
函数,returns ResponseBody。
您可能想要区分:
HttpClientErrorException
(HTTP-状态 >=400)或 HttpServerErrorException
(HTTP-状态 >=500)甚至 RestClientException
.
此外,还有一个关于定义您自己的 ErrorHandler 的好文档,see this link