在我的测试中,使用SimpleMappingExceptionResolver
无法登录MissingServletRequestParameterException
,我结合@ControllerAdvice
和Filter
做记录。
使用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;
}
}
......
}
的logback配置
<logger name="global_controller_exception_logger" level="info"/>
<logger name="global_filter_exception_logger" level="info"/>
您可以完整的代码查看my gist。
那么使用这种方法将会错过哪些例外,并且有什么方法可以获得这些方法? – 2015-08-25 07:54:45
好点。我很久没有使用过春天了,不记得了。我应该在上面包含更多信息。我最好的猜测就是从'RuntimeException'派生的异常,正如我上面所暗示的。 – 2015-08-25 11:16:38