![](/img/trans.png)
[英]How can I get a body data from the request in an ExceptionHandler in Spring Boot?
[英]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.