如何从 Spring Boot 中的 ExceptionHandler 中的请求获取正文数据?

Die*_*tor 2 java spring exception spring-boot

我有一个 @RestControllerAdvice,我在其中处理 Spring Boot 中的异常。我想记录通过请求正文发送的信息。如何从 Spring WebRequest 获取此信息?

这是我的示例异常处理程序。

@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);
}
Run Code Online (Sandbox Code Playgroud)

}

@M.Deinum 我尝试使用 ContentCachingRequestWrapper,但我无法访问正文内容。contentCachingRequestWrapper.getContentAsByteArray() 方法返回 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();
    }
Run Code Online (Sandbox Code Playgroud)

lan*_*ell 7

关于使用的评论ContentCachingRequestWrapper是准确的,这是使用应该有效的控制器建议的实现。

@Component
public class MyFilter implements Filter {
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
  throws IOException, ServletException {
     ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper(
    (HttpServletRequest) servletRequest);

     filterChain.doFilter(contentCachingRequestWrapper, servletResponse);
  }
}
Run Code Online (Sandbox Code Playgroud)

建议

@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

  @Override
  protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
  HttpStatus status, WebRequest request) {

    ContentCachingRequestWrapper nativeRequest = (ContentCachingRequestWrapper) ((ServletWebRequest) request).getNativeRequest();
    String requestEntityAsString = new String(nativeRequest.getContentAsByteArray());

    log.debug(requestEntityAsString);

    return super.handleMethodArgumentNotValid(ex, headers, status, request);
  }
}
Run Code Online (Sandbox Code Playgroud)