简体   繁体   English

如何在springboot(REST)的ExceptionHandler类中获取请求体数据

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

I have a class annotated with @ControllerAdvice and methods annotated with @ExceptionHandler to handle exceptions thrown by the service code.我有一个用@ControllerAdvice 注释的类和用@ExceptionHandler 注释的方法来处理服务代码抛出的异常。 When handling these exceptions, I would like to get the @RequestBody that was part of the request POST operations.在处理这些异常时,我想获得作为请求 POST 操作一部分的 @RequestBody。

I tried by creating POJO class for the request sent and tried to retrieve inside exception handler class but it returns null.我尝试为发送的请求创建 POJO 类,并尝试在异常处理程序类中检索,但它返回 null。

Followed the same solution given in this query~ How to get the @RequestBody in an @ExceptionHandler (Spring REST)遵循此查询中给出的相同解决方案〜 如何在@ExceptionHandler(Spring REST)中获取@RequestBody

It doesn't work.它不起作用。

I also tried with httpServertRequest, even that return null for the request data.我也尝试使用 httpServertRequest,即使请求数据返回 null。

I want to get the request body of the api inside ExceptionHandler method.我想在 ExceptionHandler 方法中获取 api 的请求正文。 Based on the request body data I have to return the error response.根据请求正文数据,我必须返回错误响应。

I also want the query param data to be used inside ExceptionHandler method.我还希望在 ExceptionHandler 方法中使用查询参数数据。

Please provide with a solution.请提供解决方案。 Thank you.谢谢你。

The Stream of Request Body only read once, so you can't retrieve it for the second time inside ControllerAdvice, thus cache the request body with ContentCachingRequestWrapper first. Request Body 的 Stream 只读取了一次,所以不能在 ControllerAdvice 里面第二次取回,所以先用 ContentCachingRequestWrapper 缓存请求体。 Create a new Spring component like this:像这样创建一个新的 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);
    }
}

then in @ControllerAdvice make your @ExceptionHandler accept ContentCachingRequestWrapper as parameter.然后在 @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