The default error handler of RestTemplate DefaultResponseErrorHandler already reads the response body and sets it in the HttpStatusCodeException object that it throws.
try {
restTemplate.getForObject("http://...", String.class);
} catch (HttpStatusCodeException e) {
System.out.println("Received error: " + e.getResponseBodyAsString());
}
If you want to always log the response body on error without requiring to catch HttpStatusCodeException, you can extend the default error handler.
public static class LoggingErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (HttpStatusCodeException e) {
System.out.println("Error response body is " + e.getResponseBodyAsString());
throw e;
}
}
}
Use the above error handler while instantiating rest template.
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new LoggingErrorHandler());
String response = restTemplate.getForObject("http://...", String.class);