Java Spring Rest客户端异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28710945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Rest Client Exception Handling
提问by Abhendra Singh
I am using spring RestTemplate
to consume rest services(exposed in 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.
我正在使用 springRestTemplate
来消耗休息服务(在 spring 休息中暴露)。我能够使用成功场景。但对于负面情况,服务会返回错误消息和错误代码。我需要在我的网页中显示这些错误消息。
For e.g. for invalid request, service throws HttpStatus.BAD_REQUEST
with proper messages. If i put try-catch block it goes to catch block and I am not able to get ResponseEntity
object.
例如对于无效请求,服务会抛出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();
}
How to get ResponseWrapper
for exception case?
如何获取ResponseWrapper
异常情况?
I read about CustomRestTemplate
and ResponseExtractor
from herebut could not decide which one is best for my case.
我从这里阅读CustomRestTemplate
并ResponseExtractor
从这里开始,但无法决定哪一个最适合我的情况。
采纳答案by Abhendra Singh
I found solution. HttpClientErrorException
worked for me.
我找到了解决方案。HttpClientErrorException
为我工作。
It has e.getResponseBodyAsString()
function which returns ResponseBody.
它具有e.getResponseBodyAsString()
返回 ResponseBody 的函数。
回答by phirzel
You might want to distinguish between:
您可能想区分:
HttpClientErrorException
(HTTP-Status >=400) or HttpServerErrorException
(HTTP-Status >= 500) or even RestClientException
.
HttpClientErrorException
(HTTP-Status >=400) 或HttpServerErrorException
(HTTP-Status >=500) 甚至RestClientException
.
Further on there is a good doc about defining your own ErrorHandler, see this link
进一步有关于定义自己的 ErrorHandler 的好文档,请参阅此链接