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

图1(这里的CustomExceptionResolver是我自定义的,大家可以忽略)

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

文章插图
默认HandlerExceptionResolver集合
根据
ExceptionHandlerExceptionResolver 的继承关系得到核心处理逻辑是如下方法:
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {// 这里的整个过程会先从Controller中获取所有@ExceptionHandler标注的方法中获取能够// 处理该异常的方法,如果没有会从全局异常句柄中查找ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);if (exceptionHandlerMethod == null) {return null;}// ...ServletWebRequest webRequest = new ServletWebRequest(request, response);ModelAndViewContainer mavContainer = new ModelAndViewContainer();ArrayList<Throwable> exceptions = new ArrayList<>();// 下面的流程就是执行上面的ServletInvocableHandlerMethodtry {// Expose causes as provided arguments as wellThrowable exToExpose = exception;while (exToExpose != null) {exceptions.add(exToExpose);Throwable cause = exToExpose.getCause();exToExpose = (cause != exToExpose ? cause : null);}Object[] arguments = new Object[exceptions.size() + 1];exceptions.toArray(arguments);// efficient arraycopy call in ArrayListarguments[arguments.length - 1] = handlerMethod;// 执行方法调用(执行@ExceptionHandler标注的方法,这方法执行过程中可能就直接向客户端返回数据了,比如基于Rest接口)exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, arguments);} catch (Throwable invocationEx) {// ...return null;}if (mavContainer.isRequestHandled()) {return new ModelAndView();} else {// 构建ModelAndView对象ModelMap model = mavContainer.getModel();HttpStatus status = mavContainer.getStatus();ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, status);mav.setViewName(mavContainer.getViewName());if (!mavContainer.isViewReference()) {mav.setView((View) mavContainer.getView());}if (model instanceof RedirectAttributes) {Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);}return mav;}}上面大体上就是Controller发生异常后的处理逻辑 。
完毕!!!




推荐阅读