Skip to content

Instantly share code, notes, and snippets.

@daniel-shuy
Created August 17, 2020 15:55
Show Gist options
  • Save daniel-shuy/4c421b93b59054ba75fa8a0fbc8f75c1 to your computer and use it in GitHub Desktop.
Save daniel-shuy/4c421b93b59054ba75fa8a0fbc8f75c1 to your computer and use it in GitHub Desktop.
Spring HTTP Client ErrorLoggingInterceptor

HTTP Client interceptor that logs the target URI, HTTP status, response body and request body, to aid debugging.

@Component
@Slf4j
public class ErrorLoggingInterceptor implements ClientHttpRequestInterceptor {
@Nonnull
@Override
public ClientHttpResponse intercept(@Nonnull HttpRequest request, @Nonnull byte[] body, ClientHttpRequestExecution execution)
throws IOException {
var response = execution.execute(request, body);
var statusCode = response.getStatusCode();
if (!statusCode.is2xxSuccessful()) {
var targetUri = request.getURI();
var responseBody = IOUtils.toString(response.getBody(), StandardCharsets.UTF_8);
var requestBody = new String(body, StandardCharsets.UTF_8);
log.error("HTTP request error:"
+ "\n\tTarget URI: {}"
+ "\n\tHTTP Status: {} ({})"
+ "\n\tResponse Body: {}"
+ "\n\tRequest Body: {}",
targetUri, statusCode.value(), statusCode.getReasonPhrase(), responseBody, requestBody);
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment