Spring Rest客户端exception处理

我使用spring RestTemplate来使用rest服务(在spring rest中暴露)。 我能够消耗成功的场景。 但对于负面情况,服务会返回错误消息和错误代码。 我需要在我的网页中显示这些错误消息。

例如,对于无效请求,服务会使用适当的消息抛出HttpStatus.BAD_REQUEST 。 如果我把try-catch块转到catch块,我就无法得到ResponseEntity对象。

 try { ResponseEntity<ResponseWrapper> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, new ParameterizedTypeReference<ResponseWrapper>() { }); responseEntity.getStatusCode(); } catch (Exception e) { //TODO How to get response here, so that i can get error messages? e.printStackTrace(); } 

如何获取ResponseWrapperexception情况?

我从这里读到了CustomRestTemplateResponseExtractor ,但无法确定哪一个最适合我的情况。

我找到了解决方案 HttpClientErrorException对我HttpClientErrorException

它有e.getResponseBodyAsString()函数,它返回ResponseBody。

您可能想要区分:

HttpClientErrorException (HTTP-Status> = 400)或HttpServerErrorException (HTTP-Status> = 500)或甚至RestClientException

还有一个关于定义自己的ErrorHandler的好文档, 请参阅此链接