1、第一步,找到是哪个类解析的这两个注解?
ExceptionHandlerExceptionResolver(会在WebMvcAutoConfiguration中注册)
-InitializingBean(实现了afterPropertiesSet)
-AbstractHandlerMethodExceptionResolver
-AbstractHandlerExceptionResolver
-HandlerExceptionResolver
afterPropertiesSet
-
initExceptionHandlerAdviceCache
获取ControllerAdvice标注的bean,并包装成ExceptionHandlerMethodResolver对象;
添加到exceptionHandlerAdviceCache中,保持对应的方法处理器;
-ExceptionHandlerMethodResolver
解析方法对应的异常处理
2、当上下文启动之后,会触发DispatcherServlet的onRefresh方法;
onRefresh;
-initStrategies;
-initHandlerExceptionResolvers;
在这个方法中,从上下文中找到HandlerExceptionResolver类型的bean,赋值给handlerExceptionResolvers,并进行排序;
3、接下来看看DispatcherServlet的请求流程:
doService
-
doDispatch
-
processDispatchResult(如果有异常并且不为ModelAndViewDefiningException)
-
processHandlerException(执行HandlerExceptionResolver#resolveException)
ok,至此,一个全局的异常处理的流程就清楚了。