小编Die*_*tor的帖子

如何从 Spring Boot 中的 ExceptionHandler 中的请求获取正文数据?

我有一个 @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);
}
Run Code Online (Sandbox Code Playgroud)

}

@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); …
Run Code Online (Sandbox Code Playgroud)

java spring exception spring-boot

2
推荐指数
1
解决办法
9879
查看次数

标签 统计

exception ×1

java ×1

spring ×1

spring-boot ×1