We are using spring version 4.3.9 and using RestTemplate for rest calls. We have test cases where we intentionally have badly formatted content when we call a particular endpoint (the request itself is fine, the contents of the payload are intentionally badly formatted).
Anyway, under these conditions, the endpoint returns a response object with meaningful information in addition to tagging it as a 400 error (Bad Request). RestTemplate sees the 400 error and throws a HttpClientErrorException. Since this exception is thrown, the response object is null.
When I perform the identical request (bad data and all) using regular apache HttpClient call, there is no exception thrown (inspite of the 400 error) and the request object is returned with meaningful (useful) information.
When executed with extensive spring debug logging setup, I can see the meaningful information was definitely returned from the RestTemplate client call, however RestTemplate throws the exception and therefore does not seem to make the message avaliable to the caller.
Is it possible the meaningful message is buried in the exception response somewhere? If so, how do I extract it?
If not returned as part of the exception, is there a way I can keep RestTemplate from throwing this exception but instead just returning the response object like HttpClient is doing?
Thanks for any response!
Is it possible the meaningful message is buried in the exception response somewhere?
Yes, the body of the response is in the exception object.
To get the body of the response, you can use:
HttpClientErrorException.getResponseBodyAsString()
or HttpClientErrorException.getResponseBodyAsByteArray()
methods.
Check this