Здравствуйте. Приложение основано на фреймфорке
Spring
. Через
RestTemplate
приложение общается с другими приложением (REST). Почему-то, если ответ отправляется код
HTTP
4xx и
5xx, то выбрасывается
ResourceAccessException
, и особо нельзя никакой информации получить: не тело ответа, ни код. Хотелось бы использовать удобные классы
HttpClientErrorException
и
HttpServerErrorException
.
Версия
Spring
-
5.1.4.RELEASE.
Версия
Spring Boot
(на всякий случай) -
2.1.2.RELEASE.
Конфигурация бина
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
у вылетающего эксепшена, в случае если вызываемый
REST API
выкинул
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
Причём, как мне кажется, раньше работало.