M
M
MaxLich2019-11-22 18:31:51
Java
MaxLich, 2019-11-22 18:31:51

Why does RestTemplate throw ResourceAccessException instead of HttpClientErrorException or HttpServerErrorException?

Hello. The application is based on a framework Spring. Through RestTemplatethe application communicates with other applications (REST). For some reason, if the response is sent code HTTP4xx and 5xx , then it is thrown out ResourceAccessException, and you can’t get any information in particular: neither the response body nor the code. I would like to use convenient classes HttpClientErrorExceptionand HttpServerErrorException.
Version Spring- 5.1.4.RELEASE .
The version Spring Boot(just in case) is 2.1.2.RELEASE .
Bean configuration RestTemplate:

@Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingHttpRequestInterceptor());
        restTemplate.setInterceptors(interceptors);
        restTemplate.getMessageConverters().add(0, mappingJackson2HttpMessageConverter());
        return restTemplate;
    }

This is the code to send a request and handle response errors:
ResponseEntity<R> response = null;
        try {
            response = restTemplate.exchange(url, httpMethod, new HttpEntity<>(objectToSend, headers), returnedObjectClass);
        } catch (HttpClientErrorException ex) {

            if (ex.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw new ResourceAccessException("invalid_token", new HttpRetryException("invalid_token", HttpStatus.UNAUTHORIZED.value()));
            }

            if (restRequestType == RestRequestType.GET_BY_ID && ex.getStatusCode() == HttpStatus.NOT_FOUND) {
                return null;
            }
            throwRestReqExWithHttpErrExInfo(ex);

        } catch (HttpServerErrorException ex) {

            if (restRequestType == RestRequestType.UPDATE && isOptimisticLocking(ex)) {
                throw new OptimisticEntityLockException(objectToSend, "OptimisticLocking");
            }

            throwRestReqExWithHttpErrExInfo(ex);
        }

detailMessageat the departing exception, if the callee REST APIthrew 404:
I/O error on GET request for "http://localhost:9999/myproject-rest/api/v1/docs/1300": http://localhost:9999/myproject-rest/api/v1/docs/1300

Inside this eksepshena lies java.io.FileNotFoundException
And, as it seems to me, it used to work.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question