Reading httprequest content from spring exception handler

后端 未结 3 602
野性不改
野性不改 2021-02-01 23:36

I Am using Spring\'s @ExceptionHandler annotation to catch exceptions in my controllers.

Some requests hold POST data as plain XML string written to the req

3条回答
  •  遥遥无期
    2021-02-01 23:43

    Recently I faced this issue and solved it slightly differently. With spring boot 1.3.5.RELEASE

    The filter was implemented using the Spring class ContentCachingRequestWrapper. This wrapper has a method getContentAsByteArray() which can be invoked multiple times.

    import org.springframework.web.util.ContentCachingRequestWrapper;
    public class RequestBodyCachingFilter implements Filter {
    
        public void init(FilterConfig fc) throws ServletException {
        }
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(new ContentCachingRequestWrapper((HttpServletRequest)request), response);
        }
    
        public void destroy() {
        }
    }
    

    Added the filter to the chain

    @Bean
    public RequestBodyCachingFilter requestBodyCachingFilter() {
        log.debug("Registering Request Body Caching filter");
        return new RequestBodyCachingFilter();
    }
    

    In the Exception Handler.

    @ControllerAdvice(annotations = RestController.class)
    public class GlobalExceptionHandlingControllerAdvice {
        private ContentCachingRequestWrapper getUnderlyingCachingRequest(ServletRequest request) {
            if (ContentCachingRequestWrapper.class.isAssignableFrom(request.getClass())) {
                return (ContentCachingRequestWrapper) request;
            }
            if (request instanceof ServletRequestWrapper) {
                return getUnderlyingCachingRequest(((ServletRequestWrapper)request).getRequest());
            }
            return null;
        }
    
        @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
        @ExceptionHandler(Throwable.class)
        public @ResponseBody Map conflict(Throwable exception, HttpServletRequest request) {
            ContentCachingRequestWrapper underlyingCachingRequest = getUnderlyingCachingRequest(request);
            String body = new String(underlyingCachingRequest.getContentAsByteArray(),Charsets.UTF_8);
            ....
        }
    }
    

提交回复
热议问题