spring - RestTemplate 包括异常中的主体
问题描述
假设我用 RestTemplate 调用一个 web 服务,它返回 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"
}
目前 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 异常消息中?
谢谢!
解决方案
可能是这样的(没有自定义错误处理程序)
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);
}
推荐阅读
- reactjs - 用于反应应用程序的 HTTPS/SSL
- machine-learning - 图像分类中的输出层
- python - 如何在启动/停止时为 EC2 实例自动分配/删除弹性 IP
- node.js - heroku deploy vue app TypeError: Object prototype may only be an Object or null: /dist/
- c# - 带有 C# 库的 GigE Vision 相机 开源
- reactjs - 如何保存旧的状态值反应
- amazon-web-services - 从公共 Internet 发布 AWS SQS 消息
- .net - 在 IIS 上托管后发送 403 状态代码时出现错误消息
- javascript - java.lang.double 错误 - React Native(仅在 android 中出现)
- pytorch - 删除中间张量会影响 PyTorch 中的计算图吗?