I have a @RestControllerAdvice where I handle an Exception in Spring Boot. I would like to log an information that is sent through request body. How can I get this information from a spring WebRequest?
This is my sample exception handler.
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
// I want to add something here that I could log an info that is in the request body.
return super.handleMethodArgumentNotValid(ex, headers, status, request);
}
}
@M.Deinum I tried to use ContentCachingRequestWrapper, But I could not have acess to body content. The method contentCachingRequestWrapper.getContentAsByteArray() returns null.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper((HttpServletRequest) request);
wrappedRequest.getContentAsByteArray();
wrappedRequest.getInputStream();
chain.doFilter(wrappedRequest, response);
} finally {
LoggingContext.clear();
}