在我的测试中,使用SimpleMappingExceptionResolver
can't log MissingServletRequestParameterException
,我结合@ControllerAdvice
并Filter
做 log。
用于ControllerAdvice
捕获 Spring MVC 控制器中引发的 Throwable。
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger("global_controller_exception_logger");
@ExceptionHandler(value = Throwable.class)
public void defaultErrorHandler(Throwable e) throws Throwable {
// If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation
(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
// Otherwise log exception
logger.error("global controller default exception handler", e);
throw e;
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public void httpBadRequest(Exception e, HttpServletRequest request) throws Exception {
StringBuffer requestURL = request.getRequestURL();
logger.warn("{} HTTP Status 400 - {}", requestURL, e.getMessage());
throw e;
}
}
用于Filter
捕获额外的异常。
@WebFilter(
filterName = "ExceptionLogFilter",
urlPatterns = "/*",
dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR}
)
public class ExceptionLogFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger("global_filter_exception_logger");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (IOException | ServletException e) {
logger.error("bad thing happened during doFilter", e);
throw e;
}
}
......
}
回退配置
<logger name="global_controller_exception_logger" level="info"/>
<logger name="global_filter_exception_logger" level="info"/>
您可以查看我的要点以获取完整代码。