Below is the code snippet; basically, I am trying to propagate the exception when the error code is anything other than 200.
ResponseEntity<Object> response = restTemplate.exchange(url.toString().replace("{version}", version),
HttpMethod.POST, entity, Object.class);
if(response.getStatusCode().value()!= 200){
logger.debug("Encountered Error while Calling API");
throw new ApplicationException();
}
However in the case of a 500 response from the server I am getting the exception
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
Do I really need to wrap the rest template exchange method in try? What would then be the purpose of codes?
Here is my POST method with HTTPS which returns a response body for any type of bad responses.
Spring cleverly treats http error codes as exceptions, and assumes that your exception handling code has the context to handle the error. To get exchange to function as you would expect it, do this:
This will return all the expected results from the response.
You should catch a
HttpStatusCodeException
exception:You want to create a class that implements
ResponseErrorHandler
and then use an instance of it to set the error handling of your rest template:Also, Spring has the class
DefaultResponseErrorHandler
, which you can extend instead of implementing the interface, in case you only want to override thehandleError
method.Take a look at its source code to have an idea of how Spring handles HTTP errors.
The code of exchange is below:
Exception
RestClientException
hasHttpClientErrorException
andHttpStatusCodeException
exception.So in
RestTemplete
there may occureHttpClientErrorException
andHttpStatusCodeException
exception. In exception object you can get exact error message using this way:exception.getResponseBodyAsString()
Here is the example code:
Here is the code description:
In this method you have to pass request and response class. This method will automatically parse response as requested object.
First of All you have to add message converter.
Then you have to add
requestHeader
. Here is the code:Finally, you have to call exchange method:
For prety printing i used Gson library. here is the gradle :
compile 'com.google.code.gson:gson:2.4'
You can just call the bellow code to get response:
Here is the full working code:
Thanks :)
Another solution is the one described here at the end of this post by "enlian": http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate