Servlet规范规定了当web应用发生异常时必须可以指明, 并肯定了该如何处理, 规定了错误信息应该包含的内容和展现页面的方式.(详细能够参考servlet规范文档)html
<error-code>
<exception-type>
<location>
全部的请求必然以某种方式转化为响应.java
@ResponseStatus
注解能够映射某一异常到特定的HTTP状态码@ExceptionHandler
注解使其用来处理异常@ControllerAdvice
方式能够统一的方式处理全局异常一.接口HandlerExceptionResolver
ios
该接口定义了Spring中该如何处理异常. 它只有一个方法resolveException()
, 接口源码以下:web
// 由对象实现的接口,这些对象能够解决在处理程序映射或执行期间引起的异常,在典型的状况下是错误视图。在应用程序上下文中,实现器一般被注册为bean。 // 错误视图相似于JSP错误页面,可是能够与任何类型的异常一块儿使用,包括任何已检查的异常,以及针对特定处理程序的潜在细粒度映射。 public interface HandlerExceptionResolver { @Nullable ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex); }
Spring 为该接口提供了若干实现类以下:spring
HandlerExceptionResolverComposite 委托给其余HandlerExceptionResolver的实例列表 AbstractHandlerExceptionResolver 抽象基类 AbstractHandlerMethodExceptionResolver 支持HandlerMethod处理器的抽象基类 ExceptionHandlerExceptionResolver 经过 @ExceptionHandler 注解的方式实现的异常处理 DefaultHandlerExceptionResolver 默认实现, 处理spring预约义的异常并将其对应到错误码 ResponseStatusExceptionResolver 经过 @ResponseStatus 注解映射到错误码的异常 SimpleMappingExceptionResolver 容许将异常类映射到视图名
二. DefaultHandlerExceptionResolver
spring-mvc
这个类是Spring提供的默认实现, 用于将一些常见异常映射到特定的状态码. 这些状态码定义在接口HttpServletResponse
中, 下面是几个状态码的代码片断mvc
public interface HttpServletResponse extends ServletResponse { ... public static final int SC_OK = 200; public static final int SC_MOVED_PERMANENTLY = 301; public static final int SC_MOVED_TEMPORARILY = 302; public static final int SC_FOUND = 302; public static final int SC_UNAUTHORIZED = 401; public static final int SC_INTERNAL_SERVER_ERROR = 500; ... }
实际上, DefaultHandlerExceptionResolver
中并无直接实现接口的resolveException
方法, 而是实现了抽象类AbstractHandlerExceptionResolver
的doResolveException()
方法, 后者则在实现了接口的方法中委托给抽象方法doResolveException
, 这个方法由子类去实现.app
AbstractHandlerExceptionResolver
的resolveException
方法代码以下:ide
@Override @Nullable public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { // 判断是否当前解析器可用于handler if (shouldApplyTo(request, handler)) { prepareResponse(ex, response); ModelAndView result = doResolveException(request, response, handler, ex); if (result != null) { // Print warn message when warn logger is not enabled... if (logger.isWarnEnabled() && (this.warnLogger == null || !this.warnLogger.isWarnEnabled())) { logger.warn("Resolved [" + ex + "]" + (result.isEmpty() ? "" : " to " + result)); } // warnLogger with full stack trace (requires explicit config) logException(ex, request); } return result; } else { return null; } }
接下来咱们看DefaultHandlerExceptionResolver
实现的doResolveException
方法. 代码以下;spring-boot
@Override @Nullable protected ModelAndView doResolveException( HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { try { if (ex instanceof HttpRequestMethodNotSupportedException) { return handleHttpRequestMethodNotSupported( (HttpRequestMethodNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotSupportedException) { return handleHttpMediaTypeNotSupported( (HttpMediaTypeNotSupportedException) ex, request, response, handler); } .... else if (ex instanceof NoHandlerFoundException) { return handleNoHandlerFoundException( (NoHandlerFoundException) ex, request, response, handler); } ..... } catch (Exception handlerEx) { if (logger.isWarnEnabled()) { logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", handlerEx); } } return null; }
能够看到代码中使用了大量的分支语句, 其实是将方法传入的异常类型经过instanceof运算符测试, 经过测试的转化为特定的异常. 并调用处理该异常的特定方法. 咱们挑一个好比处理NoHandlerFoundException
这个异常类的方法, 这个方法将异常映射为404错误.
protected ModelAndView handleNoHandlerFoundException(NoHandlerFoundException ex, HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException { pageNotFoundLogger.warn(ex.getMessage()); response.sendError(HttpServletResponse.SC_NOT_FOUND); //设置为404错误 return new ModelAndView(); //返回个空视图 }
上面分析了Spring默认的异常处理实现类DefaultHandlerExceptionResolver
.它处理的异常是Spring预约义的几种常见异常, 它将异常对应到HTTP的状态码. 而对于不属于这些类型的其余异常, 咱们可使用ResponseStatusExceptionResolver
来处理, 将其对应到HTTP状态码.
三. ResponseStatusExceptionResolver
如何使用?
@GetMapping("/responseStatus") @ResponseBody public String responseStatus() throws MyException { throw new MyException(); } @ResponseStatus(code = HttpStatus.BAD_GATEWAY) public class MyException extends Exception{}
只须要在异常上使用@ResponseStatus
注解便可将特定的自定义异常对应到Http的状态码.
四. ExceptionHandlerExceptionResolver
使用相似于普通的controller方法, 使用@ExceptionHandler
注解的方法将做为处理该注解参数中异常的handler. 好比, 在一个controller中, 咱们定义一个处理NPE的异常处理handler方法, 能够用来处理该controller中抛出的NPE. 代码以下:
@GetMapping("/npe1") @ResponseBody public String npe1() throws NullPointerException { throw new NullPointerException(); } @GetMapping("/npe2") @ResponseBody public String npe2() throws NullPointerException { throw new NullPointerException(); } @ExceptionHandler(value = {NullPointerException.class}) @ResponseBody public String npehandler(){ return "test npe handler"; }
不管是请求/npe1仍是请求/npe2, 系统都会抛出异常, 并交给对应的处理程序npehandler
去处理. 使用@ExceptionHandler(value = {NullPointerException.class})
注解的方法能够处理本controller范围内的全部方法排除的npe异常, 若是要将其做为应用中全部controller的异常处理器, 就要将其定义在@ControllerAdvice
注解的类中.
@ControllerAdvice public class ControllerAdvicer { @ExceptionHandler(value = {NullPointerException.class}) @ResponseBody public String npehandler(){ return "test npe handler in advice"; } }
要了解其原理, 须要查看ExceptionHandlerExceptionResolver
中的方法doResolveHandlerMethodException
@Override @Nullable protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) { // 获取异常对用的处理器, 就是@ExceptionHandler注解的方法包装, 注意参数handlerMethod, 在方法内部, 它将用来获取所在Controller的信息 ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception); if (exceptionHandlerMethod == null) { return null; } if (this.argumentResolvers != null) { exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); } if (this.returnValueHandlers != null) { exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers); } ServletWebRequest webRequest = new ServletWebRequest(request, response); ModelAndViewContainer mavContainer = new ModelAndViewContainer(); try { if (logger.isDebugEnabled()) { logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod); } Throwable cause = exception.getCause(); // 调用异常处理handler的方法. if (cause != null) { // Expose cause as provided argument as well exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, cause, handlerMethod); } else { // Otherwise, just the given exception as-is exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod); } } catch (Throwable invocationEx) { // Any other than the original exception is unintended here, // probably an accident (e.g. failed assertion or the like). if (invocationEx != exception && logger.isWarnEnabled()) { logger.warn("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx); } // Continue with default processing of the original exception... return null; } if (mavContainer.isRequestHandled()) { return new ModelAndView(); } else { 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; } }
能够看到在两个中文注释的地方, 其一是方法的开始部分获取到了异常的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); } }
从processDispatchResult
方法中能够看到, 若是参数exception
不为null, 则会处理异常, 对于ModelAndViewDefiningException
类型的异常单独处理, 对于其余类型的异常, 转交给processHandlerException
方法处理, 这个方法就是异常处理逻辑的核心.
@Nullable protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) throws Exception { // Success and error responses may use different content types request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); // 使用注册的Resolver处理 ModelAndView exMv = null; if (this.handlerExceptionResolvers != null) { for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) { exMv = resolver.resolveException(request, response, handler, ex); if (exMv != null) { break; } } } if (exMv != null) { if (exMv.isEmpty()) { request.setAttribute(EXCEPTION_ATTRIBUTE, ex); return null; } // We might still need view name translation for a plain error model... if (!exMv.hasView()) { String defaultViewName = getDefaultViewName(request); if (defaultViewName != null) { exMv.setViewName(defaultViewName); } } if (logger.isTraceEnabled()) { logger.trace("Using resolved error view: " + exMv, ex); } if (logger.isDebugEnabled()) { logger.debug("Using resolved error view: " + exMv); } WebUtils.exposeErrorRequestAttributes(request, ex, getServletName()); return exMv; } throw ex; }
从上面代码能够看到, this.handlerExceptionResolvers
就是在程序启动时初始化注册的, spring经过遍历Resolver列表的方式处理异常, 若是返回结果不为null, 说明处理成功, 就跳出循环.
Spring的异常解析器实现所有继承自接口ResponseStatusExceptionResolver
, 上面咱们详细了解了该接口在Spring中的几种实现, 好比处理预约义异常的DefaultHandlerExceptionResolver
, 能够映射异常到状态码的ResponseStatusExceptionResolver
, 还有功能更为强大的ExceptionHandlerExceptionResolver
. 同时也简单了解了其使用方式,使用@ExceptionHandler
来将方法标记为异常处理器, 结合@ControllerAdvice
处理全局异常.
最后咱们探究了异常处理器的加载和处理方式, 咱们知道了其经过 DispatcherServlet
的初始化方法initHandlerMappings
完成加载器列表的注册初始化, 而且在具体处理请求的doDispatch
中检测异常, 最终processDispatchResult
方法委托给processHandlerException
, 该方法循环注册的异常处理器列表完成处理过程.