Dodji
Dodji

Reputation: 80

Can I include the restTemplate request body inside restTemplate.setErrorHandler?

Here In the below simple code of RestTemplate's errorHandler I want to include the request body inside the log

I want to keep the code clean and not using the error handler out side restTemplate configuration class. So the only way i found is to handel it from rest template caller/user, WDYT?

@Configuration
public class HTTPConfiguration {
...

 restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {

                if (response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR) {

                    LOGGER.error("Server error: {} {}", response.getStatusCode(), response.getStatusText());

                } else if (response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR) {

                    LOGGER.error("Client error: {} {}", response.getStatusCode(), response.getStatusText());
                }
            }

            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {

                return (response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR
                        || response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR);
            }
});


...
}

Upvotes: 1

Views: 570

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

The straight answer is no, ResponseErrorHandler is an interface and only has three methods, the best you can get is request url and request method docs

handleError(ClientHttpResponse response)

Handle the error in the given response.

handleError(java.net.URI url, HttpMethod method, ClientHttpResponse response)

Alternative to handleError(ClientHttpResponse) with extra information providing access to the request URL and HTTP method.

handleError(java.net.URI url, HttpMethod method, ClientHttpResponse response)

Indicate whether the given response has any errors.

And ResponseErrorHandler has two implementation classes DefaultResponseErrorHandler, ExtractingResponseErrorHandler but none of them has method with HttpEntity as an argument DefaultResponseErrorHandler,and ExtractingResponseErrorHandler

Upvotes: 3

Related Questions