Skip to main content

Posts

How to avoid HttpStatusCodeException using Spring RestTemplate

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 tha