我正在寻找一种方法将我的所有请求和响应记录到数据库中(1条记录=1个请求+1个响应)。
我的用例详细信息:
-
在数据库中记录请求URL、参数、IP、开始日期等。
-
更新数据库记录(请求完成时)并保存响应,
例外情况、结束日期等。
我正在尝试使用自定义onceperRequestFilter,它几乎可以正常工作。但是我在处理用注释注释的异常方面有问题
@ResponseStatus
。这种异常(在控制器中抛出)在我的自定义dofilter方法中无法捕获。您知道如何在过滤器中捕获这些异常吗?除非我用其他方法来做?
审核筛选器:
@Component
public class AuditFilter extends OncePerRequestFilter {
private Logger logger = Logger.getLogger(AuditFilter.class.getName());
private RequestAuditRepository repository;
AuditFilter(RequestAuditRepository repository) {
this.repository = repository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
doFilterWrapped(wrapRequest(request), wrapResponse(response), filterChain);
}
private void doFilterWrapped(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response, FilterChain filterChain)
throws ServletException, IOException {
RequestAuditLog requestAuditLog = new RequestAuditLog();
String catchedExceptionMsg = null;
try {
beforeRequest(requestAuditLog, request);
filterChain.doFilter(request, response);
}
catch (Exception e) {
catchedExceptionMsg = e.getMessage();
throw e;
}
finally {
afterRequest(requestAuditLog, catchedExceptionMsg, request, response);
response.copyBodyToResponse();
}
}
...
}
BadRequestException:
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}