简体   繁体   English

如何找出@ExceptionHandler不起作用的原因?

[英]How to find out why @ExceptionHandler don't work?

In my project, when I add a exception handler method in my controller, it doesn't work. 在我的项目中,当我在控制器中添加异常处理程序方法时,该方法无效。 But if I move this code to a demo project which have the same Spring version, missingParamterHandler method works well. 但是,如果我将此代码移到具有相同Spring版本的演示项目中,则missingParamterHandler方法效果很好。 Can anyone help me handle this problem? 谁能帮我解决这个问题?

@Controller
@RequestMapping("/order")
public class OrderControlle{

    @ExceptionHandler(Exception.class)
    public @ResponseBody ClientResult missingParamterHandler(Exception exception) {
    /*inspect and exception and obtain meaningful message*/
    ClientResult clientResult = new ClientResult();
    clientResult.getBstatus().setCode(BstatusCode.PARAM_ERR);
    return clientResult; 
    }
}

I try debug, and find in Spring's DispatcherServlet.java, matchingBeans.isEmpty() returns true, is it the reason @ExceptionHandler(Exception.class) not work in my project? 我尝试调试,并在Spring的DispatcherServlet.java中找到,matchingBeans.isEmpty()返回true,这是@ExceptionHandler(Exception.class)在我的项目中不起作用的原因吗?

private void initHandlerExceptionResolvers(ApplicationContext context) {
    this.handlerExceptionResolvers = null;

    if (this.detectAllHandlerExceptionResolvers) {
        // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
            // We keep HandlerExceptionResolvers in sorted order.
            OrderComparator.sort(this.handlerExceptionResolvers);
        }
    }
    .....

explicit add <bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver" /> or <mvc:annotation-driven /> to app-context.xml, solve my problem. <bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver" /><mvc:annotation-driven />显式添加到app-context.xml中,即可解决我的问题。

without this above line, spring add ExceptionResolvers as below in my project. 如果没有上述内容,请在我的项目中按以下方式春季添加ExceptionResolvers。

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM