![](/img/trans.png)
[英]Spring boot with spring data jpa. How can i perform partial update of entity from request body?
[英]How can I get a body data from the request in an ExceptionHandler in Spring Boot?
我有一个 @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);
}
}
@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);
wrappedRequest.getContentAsByteArray();
wrappedRequest.getInputStream();
chain.doFilter(wrappedRequest, response);
} finally {
LoggingContext.clear();
}
关于使用ContentCachingRequestWrapper
的评论是准确的,这是使用您的 controller 建议的实现应该有效。
@Component
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper(
(HttpServletRequest) servletRequest);
filterChain.doFilter(contentCachingRequestWrapper, servletResponse);
}
}
建议
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
ContentCachingRequestWrapper nativeRequest = (ContentCachingRequestWrapper) ((ServletWebRequest) request).getNativeRequest();
String requestEntityAsString = new String(nativeRequest.getContentAsByteArray());
log.debug(requestEntityAsString);
return super.handleMethodArgumentNotValid(ex, headers, status, request);
}
}
RequestBody 和 ResponseBody 可以只读一次所以其他方式在异常处理器中实现body访问这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.