[英]Spring Rest Client Exception Handling
I am using spring RestTemplate
to consume rest services(exposed in spring rest). 我正在使用spring
RestTemplate
来使用rest服务(在spring rest中公开)。 I am able to consume success scenarios. 我能够承受成功的情况。 But for negative scenarios, service returns error messages and error codes.
但是对于负面情况,服务将返回错误消息和错误代码。 I need to show those error messages in my web page.
我需要在网页上显示这些错误消息。
For eg for invalid request, service throws HttpStatus.BAD_REQUEST
with proper messages. 例如对于无效请求,服务会使用适当的消息抛出
HttpStatus.BAD_REQUEST
。 If i put try-catch block it goes to catch block and I am not able to get ResponseEntity
object. 如果我将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();
}
How to get ResponseWrapper
for exception case? 异常情况下如何获取
ResponseWrapper
?
I read about CustomRestTemplate
and ResponseExtractor
from here but could not decide which one is best for my case. 我从这里阅读了有关
CustomRestTemplate
和ResponseExtractor
,但无法确定哪一个最适合我的情况。
I found solution. 我找到了解决方案。
HttpClientErrorException
worked for me. HttpClientErrorException
为我工作。
It has e.getResponseBodyAsString()
function which returns ResponseBody. 它具有
e.getResponseBodyAsString()
函数,该函数返回ResponseBody。
You might want to distinguish between: 您可能要区分:
HttpClientErrorException
(HTTP-Status >=400) or HttpServerErrorException
(HTTP-Status >= 500) or even RestClientException
. HttpClientErrorException
(HTTP状态> = 400)或HttpServerErrorException
(HTTP状态> = 500)甚至RestClientException
。
Further on there is a good doc about defining your own ErrorHandler, see this link 进一步,还有关于定义自己的ErrorHandler的好文档, 请参阅此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.