【问题标题】:RestTemplate including body in exceptionRestTemplate 包括异常中的主体
【发布时间】:2019-10-10 17:12:54
【问题描述】:

假设我用 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 异常消息中?

谢谢!

【问题讨论】:

    标签: spring resttemplate


    【解决方案1】:

    可能是这样的(没有自定义错误处理程序)

    
    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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-31
      • 2019-06-02
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多