在我的项目中,当我在控制器中添加异常处理程序方法时,它不起作用。但是,如果我将此代码移动到具有相同Spring版本的演示项目,则missingParamterHandler方法可以正常工作。任何人都可以帮我解决这个问题吗?
@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;
}
}
我尝试调试,在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);
}
}
.....
答案 0 :(得分:1)
显式添加<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver" />
或<mvc:annotation-driven />
到app-context.xml,解决我的问题。
如果没有上面这行,spring会在我的项目中添加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