简体   繁体   中英

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. 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?

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.

without this above line, spring add ExceptionResolvers as below in my project.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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