【发布时间】:2015-04-26 23:17:07
【问题描述】:
我正在使用 spring RestTemplate 来消费休息服务(暴露在 spring rest 中)。我能够消费成功场景。但是对于负面情况,服务会返回错误消息和错误代码。我需要在我的网页中显示这些错误消息。
例如对于无效请求,服务会抛出 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 的信息,但无法确定哪一个最适合我的情况。
【问题讨论】:
-
您可以自己创建新的响应实体对象。新的 ResponseEntity
(HttpStatus.BAD_REQUEST);要获取错误消息,您需要捕获 RestClientException 并通过 rce.getMessage() 类似的方式获取消息。 -
你可以捕获状态码为docs.spring.io/spring/docs/current/javadoc-api/org/…的HttpStatusCodeException
-
您可以访问下面的线程。它有完整的工作代码和描述:stackoverflow.com/a/51805956/3073945
标签: java spring rest rest-client