Reputation: 227
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);
}
}
.....
Upvotes: 1
Views: 847
Reputation: 227
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
Upvotes: 1