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

How can I get a body data from the request in an ExceptionHandler in 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);
}

}

@M.Deinum 我尝试使用 ContentCachingRequestWrapper,但无法访问正文内容。方法 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();
    }

RequestBody 和 ResponseBody 可以read-only一次让其他方法在异常处理器中实现body

关于使用 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);
  }
}

建议

@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);
  }
}