【发布时间】:2014-06-11 13:58:17
【问题描述】:
我有@ControllerAdvice 类,它处理一组异常。比我们有一些其他的例外,用@ResponseStatus 注释进行注释。为了结合这两种方法,我们使用博客文章中描述的技术:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc,即在ControllerAdvice 中,我们按以下方式处理通用Exception:
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
// If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
throw e;
// Otherwise setup and send the user to a default error-view.
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;
}
它就像一个魅力,但是,使用这种技术会导致应用程序日志中出现以下文本的错误:
2014-06-11 15:51:32.907 错误 o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - 无法调用 @ExceptionHandler 方法:...
这是ExceptionHandlerExceptionResolver中的这段代码造成的:
try {
if (logger.isDebugEnabled()) {
logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
}
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception);
}
catch (Exception invocationEx) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
return null;
}
有没有人知道如何结合这两种方法来正确处理异常以避免日志中的错误?
谢谢, 一月
【问题讨论】:
-
不会简单地禁用
org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver的日志记录来解决这个问题吗? -
我想过,但它似乎不是问题的概念解决方案......
-
在不重新实现类并删除日志行的情况下,您将如何解决它?当它可以像禁用日志记录一样简单时,我们为什么要提出一个复杂的解决方案。根据您的日志记录框架,您还可以创建一个根据模式过滤消息的过滤器。
-
@M. Deinum +1 是一个简单的解决方案。 log4j.logger.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver = OFF
-
@user3730269:你能解决这个问题吗?
标签: java spring spring-mvc