- 由于body数据只能被读取一次,所以必须缓存body数据,使用ContentCachingRequestWrapper来缓存body的数据
public class FilterConfig extends GenericFilterBean {
// 只处理json数据
private static final String CONTENT_TYPE_JSON = "application/json";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
if(CONTENT_TYPE_JSON.equals(request.getContentType())){
ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
filterChain.doFilter(wrapper, servletResponse);
}
}
}
- 拦截异常
@Slf4j
@ControllerAdvice
public class WebExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result exception(Exception e, HttpServletRequest request) {
log.error("未知错误信息", e);
if (request != null && request instanceof ContentCachingRequestWrapper) {
ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request;
log.error("body数据:{}", StringUtils.toEncodedString(wrapper.getContentAsByteArray(), Charset.forName(wrapper.getCharacterEncoding())));
}
log.error("params数据:{}",request.getParameterMap());
return ResultGenerator.genErrorResult(new CustomException(CustomExceptionType.OTHER_ERROR,"未知异常"));
}
}
这样在出现异常信息时,就可以看到请求的数据体信息了,方便查找bug信息。