HTTP Client interceptor that logs the target URI, HTTP status, response body and request body, to aid debugging.
Created
August 17, 2020 15:55
-
-
Save daniel-shuy/4c421b93b59054ba75fa8a0fbc8f75c1 to your computer and use it in GitHub Desktop.
Spring HTTP Client ErrorLoggingInterceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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