Using restTemplate.exchange(uri, method, entity, responseType)
to make a REST call fails with a RestClientException
when the response is of the wrong responseType
. E.g.,
org.springframework.web.client.RestClientException: Error while extracting response for type [java.util.List<java.lang.Byte>] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Numeric value (281759) out of range of Java byte
Since this is not a RestClientResponseException
we don't seem to have access to the response data like status code and body (not even in their raw form).
Is there a way to get (raw) data from the original (unparsable) response? (for logging)
Try parsing the response as String
. See this answer - the similar concept can be used with the exchange
method.
EDIT: If the exception does not occur always and you still want to be able to map the correct responses easily, you could override the corresponding MessageConverter
(which is actually throwing the exception) and do anything you want afterwards, because the converter gives you a raw HttpInputMessage
.
Assuming you are using MappingJackson2HttpMessageConverter
it should look sth. like this (not tested though):
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
return new MappingJackson2HttpMessageConverter(objectMapper) {
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
try {
return super.read(type, contextClass, inputMessage);
} catch (HttpMessageNotReadableException e) {
// LOG here...
throw e;
}
}
};
}