Answer the question
In order to leave comments, you need to log in
Why does RestTemplate throw ResourceAccessException instead of HttpClientErrorException or HttpServerErrorException?
Hello. The application is based on a framework Spring
. Through RestTemplate
the application communicates with other applications (REST). For some reason, if the response is sent code HTTP
4xx 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 HttpClientErrorException
and 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;
}
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);
}
detailMessage
at the departing exception, if the callee REST API
threw 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
java.io.FileNotFoundException
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question