Spring RestTemplate包括异常中的主体
假设我使用RestTemplate调用一个webservice,它返回500个状态错误:Spring RestTemplate包括异常中的主体,spring,resttemplate,Spring,Resttemplate,假设我使用RestTemplate调用一个webservice,它返回500个状态错误: { "timestamp": "2019-10-10T16:51:15Z", "status": 500, "error": "Internal Server Error", "message": "Error occurred while retrieving entity with id: bb00b45c-9e17-4d75-a89a", "path": "/api/service" } 当前Res
{
"timestamp": "2019-10-10T16:51:15Z",
"status": 500,
"error": "Internal Server Error",
"message": "Error occurred while retrieving entity with id: bb00b45c-9e17-4d75-a89a",
"path": "/api/service"
}
当前RestTemplate异常消息类似于:
Caused by: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 null
at org.springframework.web.client.HttpServerErrorException.create(HttpServerErrorException.java:79)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:124)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
是否有任何方法可以在不使用自定义错误处理程序的情况下将响应主体包含在RestTemplate异常消息中
谢谢 可能是这样的(没有自定义错误处理程序)
对象映射器映射器;
试一试{
ResponseEntity response=restemplate.exchange(url,
HttpMethod.POST、requestEntity、User.class);
}捕获(HttpStatusCodeException){
列表头=e.getResponseHeaders().get(“x-app-err-id”);
字符串errorMessageId=“”;
if(header!=null&&!header.isEmpty()){
errorMessageId=header.get(0);
}
//您可以获取主体,但可以使用mapper将其反序列化到POJO中
ErrorResponseBody ErrorResponseBody=mapper.readValue(例如getResponseBodyAsString(),
ErrorResponseBody.class);
//如果需要,可以重新抛出,也可以使用响应体
抛出新的CustomException(e,HttpStatus.INTERNAL\u SERVER\u错误);
}
ObjectMapper mapper;
try {
ResponseEntity<User> response = restTemplate.exchange(url,
HttpMethod.POST, requestEntity, User.class);
} catch (HttpStatusCodeException e) {
List<String> header = e.getResponseHeaders().get("x-app-err-id");
String errorMessageId = "";
if (header != null && !header.isEmpty()) {
errorMessageId = header.get(0);
}
// You can get the body, but deserialise it using mapper into a POJO
ErrorResponseBody errorResponseBody = mapper.readValue(e.getResponseBodyAsString(),
ErrorResponseBody.class);
// You can re-throw it if you want or use the response body
throw new CustomException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}