在我的測試中,使用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