I have written a Rest client using the Spring's RestTemplate with the following code
try {
response = restTemplate.exchange( url,HttpMethod.POST, entity , JsonNode.class);
}catch (HttpStatusCodeException codeException) {
String responseBody = codeException.getResponseBodyAsString();
......................
} catch(Exception ex)
{
ex.printStackTrace();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(" { \"error\" : \"" + ex.getMessage() + "\" }" );
response = new ResponseEntity<>(node, HttpStatus.INTERNAL_SERVER_ERROR );
}
In the above code, I am not able to read the response body. This is the issue with the RestTemplate default error handler. In order to fix this issue, I have the following two options
a) Write my own Error Handler that implements ResponseErrorHandler
b) Write my own Error Handler that extends DefaultResponseErrorHandler
I prefer the second option as I have to only override the hasError method
public class MyErrorHandler extends DefaultResponseErrorHandler{
@Override
public boolean hasError( ClientHttpResponse response ) throws IOException {
// TODO Auto-generated method stub
return false;
}
}
restTemplate.setErrorHandler( new MyErrorHandler() );
I am always returning the false as I want to handle the exceptions by my own. This method can be further optimized by checking for specific HTTP Status codes.
Now instead of HttpStatusCodeException , I will get the proper ResponseEntity<?> and I can handle it accordingly to my needs.
Comments
Post a Comment