1

I was trying out RestTemplate and Retrofit2. Both the libraries throw exception in case api returns 4XX/5XX. The api when hit from postman gives a JSON response body, along with 4XX/5XX. How can I retrieve this JSON response using RestTemplate or Retrofit2.

Thanks.

komsat
  • 49
  • 2

2 Answers2

1

Use the HttpClientErrorException, HttpStatusCodeException after try block as below.

    try{
        restTemplate.exchange("url", HttpMethod.GET, null, String.class);
    }
    catch (HttpClientErrorException errorException){
        logger.info("Status code :: {}, Exception message :: {} , response body ::{}" , e.getStatusCode()
                e.getMessage(), e.getResponseBodyAsString());
    }
    catch (HttpStatusCodeException e){
        logger.info("Status code :: {}, Exception message :: {} , response body ::{}" , e.getStatusCode()
                e.getMessage(), e.getResponseBodyAsString());

    }
S. Anushan
  • 728
  • 1
  • 6
  • 12
0

For that you have to create RestTemplateError handler and register that class while creating bean for RestTemplate.

@Bean
public RestTemplate getBasicRestTemplate() {
     RestTemplate restTemplate = new RestTemplate();
     restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
     return restTemplate;
}

where your handler class has to implements ResponseErrorHandler. You can read the json response that is stored in the body.

@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateResponseErrorHandler.class);

    @Override
    public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
        return httpResponse.getStatusCode().series() == CLIENT_ERROR
                || httpResponse.getStatusCode().series() == SERVER_ERROR;
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse) throws IOException {
        if (httpResponse.getStatusCode().series() == SERVER_ERROR) {
            LOGGER.error("Handling server error response statusCode:{} ", httpResponse.getStatusCode());
        } else if (httpResponse.getStatusCode().series() == CLIENT_ERROR) {
            LOGGER.error("Handling Client error response statusCode:{} ", httpResponse.getStatusCode());
            String body;
            InputStreamReader inputStreamReader = new InputStreamReader(httpResponse.getBody(),
                    StandardCharsets.UTF_8);
            body = new BufferedReader(inputStreamReader).lines().collect(Collectors.joining("\n"));
            throw new CustomException(httpResponse.getStatusCode().toString(), httpResponse, body);
        }
    }
}
Pirate
  • 2,886
  • 4
  • 24
  • 42