簡體   English   中英

如何在springboot(REST)的ExceptionHandler類中獲取請求體數據

[英]How to get the request body data inside ExceptionHandler class in springboot(REST)

我有一個用@ControllerAdvice 注釋的類和用@ExceptionHandler 注釋的方法來處理服務代碼拋出的異常。 在處理這些異常時,我想獲得作為請求 POST 操作一部分的 @RequestBody。

我嘗試為發送的請求創建 POJO 類,並嘗試在異常處理程序類中檢索,但它返回 null。

遵循此查詢中給出的相同解決方案〜 如何在@ExceptionHandler(Spring REST)中獲取@RequestBody

它不起作用。

我也嘗試使用 httpServertRequest,即使請求數據返回 null。

我想在 ExceptionHandler 方法中獲取 api 的請求正文。 根據請求正文數據,我必須返回錯誤響應。

我還希望在 ExceptionHandler 方法中使用查詢參數數據。

請提供解決方案。 謝謝你。

Request Body 的 Stream 只讀取了一次,所以不能在 ControllerAdvice 里面第二次取回,所以先用 ContentCachingRequestWrapper 緩存請求體。 像這樣創建一個新的 Spring 組件:


@Component
public class FilterConfig extends GenericFilterBean{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
        filterChain.doFilter(wrapper, servletResponse);
    }
}

然后在 @ControllerAdvice 讓你的 @ExceptionHandler 接受 ContentCachingRequestWrapper 作為參數。


    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleDefaultException(Exception ex, ContentCachingRequestWrapper request){
        String reqBody = "your request body is " + new String(request.getContentAsByteArray(), StandardCharsets.UTF_8);
        // then do another thing you wanted for exception handling
    }

暫無
暫無

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

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