可以看到在两个中文注释的地方, 其一是方法的开始部分获取到了异常的handler, 其二是调用这个handler的方法. 调用方法应该很好理解, 我们接下来查看方法getExceptionHandlerMethod.
// 找到给定异常对应的@ExceptionHandler注解方法, 默认先在controller类的继承结构中查找, 否则继续在@ControllerAdvice注解的 bean中查找. @Nullable protected ServletInvocableHandlerMethod getExceptionHandlerMethod( @Nullable HandlerMethod handlerMethod, Exception exception) { Class<?> handlerType = null; if (handlerMethod != null) { // Local exception handler methods on the controller class itself. // To be invoked through the proxy, even in case of an interface-based proxy. handlerType = handlerMethod.getBeanType(); ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(handlerType); if (resolver == null) { resolver = new ExceptionHandlerMethodResolver(handlerType); this.exceptionHandlerCache.put(handlerType, resolver); } Method method = resolver.resolveMethod(exception); if (method != null) { return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method); } // For advice applicability check below (involving base packages, assignable types // and annotation presence), use target class instead of interface-based proxy. if (Proxy.isProxyClass(handlerType)) { handlerType = AopUtils.getTargetClass(handlerMethod.getBean()); } } // 在@ControllerAdvice注解的类中遍历查找 for (Map.Entry<ControllerAdviceBean, ExceptionHandlerMethodResolver> entry : this.exceptionHandlerAdviceCache.entrySet()) { ControllerAdviceBean advice = entry.getKey(); if (advice.isApplicableToBeanType(handlerType)) { ExceptionHandlerMethodResolver resolver = entry.getValue(); Method method = resolver.resolveMethod(exception); if (method != null) { return new ServletInvocableHandlerMethod(advice.resolveBean(), method); } } } return null; }我们可以看到,它会首先查找controller中的方法, 如果找不到才去查找@ControllerAdvice注解的bean. 也就是说controller中的handler的优先级要高于advice.
上面我们了解了几个Exceptionresolver的使用, 并通过源代码简单看了他们各自处理的原理. 但这些Resolver如何加载我们还不知道, 接下来我们重点看下他们是如何加载进去的.
四. ExceptionResolver的加载
在本系列的上一篇Spring系列(六) Spring Web MVC 应用构建分析中, 我们大致提到了DispatcherServlet的启动调用关系如下:
整理下调用关系: DispatcherServlet initHandlerMappings <-- initStrategies <-- onRefresh <--
FrameworkServlet initWebApplicationContext <-- initServletBean <--
HttpServletBean init <--
GenericServlet init(ServletConfig config)
最后的GenericServlet是servlet Api的.
正是在initStrategies方法中, DispatcherServlet做了启动的一系列工作, 除了initHandlerMappings还可以看到一个initHandlerExceptionResolvers的方法, 其源码如下:
// 初始化HandlerExceptionResolver, 如果没有找到任何命名空间中定义的bean, 默认没有任何resolver private void initHandlerExceptionResolvers(ApplicationContext context) { this.handlerExceptionResolvers = null; if (this.detectAllHandlerExceptionResolvers) { // 找到所有ApplicationContext中定义的 HandlerExceptionResolvers 包括在上级上下文中. Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false); if (!matchingBeans.isEmpty()) { this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values()); // 保持有序. AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers); } } else { try { HandlerExceptionResolver her = context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); this.handlerExceptionResolvers = Collections.singletonList(her); } catch (NoSuchBeanDefinitionException ex) { // Ignore, no HandlerExceptionResolver is fine too. } } // 确保有Resolver, 否则使用默认的 if (this.handlerExceptionResolvers == null) { this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); if (logger.isTraceEnabled()) { logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() + "': using default strategies from DispatcherServlet.properties"); } } }好了, 现在我们加载了应用程序中所有定义的Resolver. 当有请求到达时, DispatcherServlet的doDispatch方法使用请求特定的handler处理, 当handler发生异常时, 变量dispatchException的值赋值为抛出的异常, 并委托给方法processDispatchResult
doDispatch的代码, 只摘录出与本议题有关的.
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { .... try { ModelAndView mv = null; mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); }catch (Exception ex) { dispatchException = ex; } catch (Throwable err) { // As of 4.3, we're processing Errors thrown from handler methods as well, // making them available for @ExceptionHandler methods and other scenarios. dispatchException = new NestedServletException("Handler dispatch failed", err); } processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); .... } // 处理handler的结果 private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, @Nullable Exception exception) throws Exception { boolean errorView = false; // 异常处理 if (exception != null) { if (exception instanceof ModelAndViewDefiningException) { logger.debug("ModelAndViewDefiningException encountered", exception); mv = ((ModelAndViewDefiningException) exception).getModelAndView(); } else { Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, exception); errorView = (mv != null); } } // handler是否返回了view if (mv != null && !mv.wasCleared()) { render(mv, request, response); if (errorView) { WebUtils.clearErrorRequestAttributes(request); } } else { if (logger.isTraceEnabled()) { logger.trace("No view rendering, null ModelAndView returned."); } } if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { // Concurrent handling started during a forward return; } if (mappedHandler != null) { mappedHandler.triggerAfterCompletion(request, response, null); } }