SpringMVC的异常处理机制详细分析


SpringMVC的异常处理机制详细分析

文章插图

环境:Springboot2.4.12
请求入口SpringMVC的请求处理入口是DispatcherServlet,不过该Servlet不做实际的处理而实际的处理是由可其它配置的委托组件执行的 。
DispatcherServlet和任何Servlet一样,需要使用JAVA配置或web.xml根据Servlet规范进行声明和映射 。然后,DispatcherServlet使用Spring配置来发现它在请求映射、视图解析、异常处理等方面所需的委托组件 。如下配置示例:
public class CustomWebApplicationInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.register(WebConfig.class);DispatcherServlet servlet = new DispatcherServlet(context);ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);registration.setLoadOnStartup(1);registration.addMapping("/app/*");}}这里为何需要实现WebApplicationInitializer 这需要你先了解Servlet3.0+的新特性
ServletContainerInitializer
下面方法是DispatcherServlet处理的核心方法:
【SpringMVC的异常处理机制详细分析】protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {try {Exception dispatchException = null;// 1.获取HandlerMapping(该对象就是当前请求与处理程序的一个映射关系)mappedHandler = getHandler(processedRequest);// 2.获取能够处理上一步得到的处理程序HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());// 3.执行实际的调用(执行实际的处理程序)mv = ha.handle(processedRequest, response, mappedHandler.getHandler());} catch (Exception ex) {// 4.执行过程中发生异常记录到局部变量中dispatchException = ex;} catch (Throwable err) {dispatchException = new NestedServletException("Handler dispatch failed", err);}// 5.处理结果processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);}上面只是把核心的代码贴出
处理结果接着上一步中继续执行,这里就会根据上一步执行过程中是否发生异常(异常对象是否为空) 。
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,@Nullable Exception exception) throws Exception {boolean errorView = false;// 1.判断是否发生异常if (exception != null) {// 1.1.异常对象是否是该对象if (exception instanceof ModelAndViewDefiningException) {mv = ((ModelAndViewDefiningException) exception).getModelAndView();} else {// 如果不是上面的异常对象,则这里获取具体处理程序的Handler// 这里我们只考虑RequestMappingHandlerMapping情况,那么这里获取的将是HandlerMethod对象// 也就是Controller中的具体方法了Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);// 处理异常,查看下面processhandlerException方法mv = processHandlerException(request, response, handler, exception);errorView = (mv != null);}}// Did the handler return a view to render?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 forwardreturn;}if (mappedHandler != null) {// Exception (if any) is already handled..mappedHandler.triggerAfterCompletion(request, response, null);}}重点,处理异常
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,@Nullable Object handler, Exception ex) throws Exception {ModelAndView exMv = null;// 判断当前的异常解析器是否存在;也就是从容器中获取所有HandlerExceptionResolver类型对象// 这里我们就不展开了,你可以在DispatcherServlet中查看初始化过程// 默认情况下,这里集合中有如下图1中所示if (this.handlerExceptionResolvers != null) {// 遍历每一个异常处理器,谁能返回ModelAndView就结束循环// 由于DefaultErrorAttributes内部方法直接返回了null,所以这里返回的是HandlerExceptionResolverComposite// 这是聚合类,聚合了其它3个具体的解析器,所以时间处理的还是其它类并非它for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) {// 结合上面说只考虑RequestMappingHandlerMapping处理Controller的情况// 那这里合理的解析器是ExceptionHandlerExceptionResolverexMv = resolver.resolveException(request, response, handler, ex);if (exMv != null) {break;}}}// 通过上面的执行如果获取到了ModelAndView对象,下面就是判断视图对象不同的情况如何进行处理了if (exMv != null) {if (exMv.isEmpty()) {request.setAttribute(EXCEPTION_ATTRIBUTE, ex);return null;}if (!exMv.hasView()) {String defaultViewName = getDefaultViewName(request);if (defaultViewName != null) {exMv.setViewName(defaultViewName);}}WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());// 如果存在要想前端展示的视图,则返回 。return exMv;}throw ex;}


推荐阅读