1

Spring RestTemplate could set the errorHandler, which has the methods for handling errors. I have an error handler like this

try (BufferedReader buffer = new BufferedReader(new InputStreamReader(clientHttpResponse.getBody()))) {
     final String response = buffer.lines().collect(Collectors.joining("\n"));
     System.out.println(response);
  }

but it always tell me that the input stream is close. Is this a bug or do I missing something?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.