簡體   English   中英

如何從 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() 方法返回 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();
    }

關於使用ContentCachingRequestWrapper的評論是准確的,這是使用您的 controller 建議的實現應該有效。

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

RequestBody 和 ResponseBody 可以只讀一次所以其他方式在異常處理器中實現body訪問這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM