RestTemplate包括正文在内

时间:2019-10-10 17:12:54

标签: 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异常消息中?

谢谢!

1 个答案:

答案 0 :(得分: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);

}