Search code examples
springresttemplate

RestTemplate including body in exception


Suppose I call a webservice with RestTemplate and it returns 500 status error with this body:

{
"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"

}

Currently RestTemplate exception message is something like:

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)

Is there any way to include the body of the response in the RestTemplate exception message without using a custom error handler?

Thanks!


Solution

  • May be something like this (without a Custom Error Handler)

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