简体   繁体   中英

How to get json response in Java in case of 4XX and 5XX error

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.

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

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM