ref: http://blog.csdn.net/u012420654/article/details/52141807
基本概念
在 SpringMVC 中 HandlerExceptionResolver 接口负责统一异常处理。
内部构造
下面来看它的源码:
public interface HandlerExceptionResolver {
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex);
}
再来看它的继承关系:
![Alt text](http://blog.csdn.net/u012420654/article/details/1488375058097.png)
AbstractHandlerMethodExceptionResolver
该类是实现了 HandlerExceptionResolver 接口的抽象实现类。关键来看 resolveException 方法:
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
if (shouldApplyTo(request, handler)) {
prepareResponse(ex, response);
ModelAndView mav = doResolveException(request, response, handler, ex);
if (mav != null) {
logException(ex, request);
}
return mav;
} else {
return null;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
接着来看 shouldApplyTo 方法:
protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
if (handler != null) {
if (this.mappedHandlers != null &&
this.mappedHandlers.contains(handler)) {
return true;
}
if (this.mappedHandlerClasses != null) {
for (Class<?> handlerClass : this.mappedHandlerClasses) {
if (handlerClass.isInstance(handler)) {
return true;
}
}
}
}
return (this.mappedHandlers == null &&
this.mappedHandlerClasses == null);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
SimpleMappingExceptionResolver
它继承了 AbstractHandlerMethodExceptionResolver 。实现了真正的异常处理。
来看该类的 doResolveException 方法:
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
String viewName = determineViewName(ex, request);
if (viewName != null) {
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
3.设置错误状态码
applyStatusCodeIfPossible(request, response, statusCode);
}
return getModelAndView(viewName, ex, request);
} else {
return null;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
1.决定视图
private Class<?>[] excludedExceptions;
private Properties exceptionMappings;
private String defaultErrorView;
protected String determineViewName(Exception ex, HttpServletRequest request) {
String viewName = null;
if (this.excludedExceptions != null) {
for (Class<?> excludedEx : this.excludedExceptions) {
if (excludedEx.equals(ex.getClass())) {
return null;
}
}
}
if (this.exceptionMappings != null) {
viewName = findMatchingViewName(this.exceptionMappings, ex);
}
if (viewName == null && this.defaultErrorView != null) {
viewName = this.defaultErrorView;
}
return viewName;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
接着来看 findMatchingViewName 方法:
protected String findMatchingViewName(Properties exceptionMappings, Exception ex) {
String viewName = null;
String dominantMapping = null;
int deepest = Integer.MAX_VALUE;
for (Enumeration<?> names = exceptionMappings.propertyNames();
names.hasMoreElements();) {
String exceptionMapping = (String) names.nextElement();
int depth = getDepth(exceptionMapping, ex);
if (depth >= 0 &&
( depth < deepest ||
(depth == deepest &&
dominantMapping != null &&
exceptionMapping.length() > dominantMapping.length() ) )) {
deepest = depth;
dominantMapping = exceptionMapping;
viewName = exceptionMappings.getProperty(exceptionMapping);
}
}
return viewName;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
继续来看 getDepth 方法:
protected int getDepth(String exceptionMapping, Exception ex) {
return getDepth(exceptionMapping, ex.getClass(), 0);
}
private int getDepth(String exceptionMapping, Class<?> exceptionClass, int depth) {
if (exceptionClass.getName().contains(exceptionMapping)) {
return depth;
}
if (exceptionClass == Throwable.class) {
return -1;
}
return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
}
2.决定错误状态码
private Map<String, Integer> statusCodes = new HashMap<String, Integer>();
protected Integer determineStatusCode(HttpServletRequest request, String viewName) {
if (this.statusCodes.containsKey(viewName)) {
return this.statusCodes.get(viewName);
}
return this.defaultStatusCode;
}
3.设置错误状态码
public static final String ERROR_STATUS_CODE_ATTRIBUTE =
"javax.servlet.error.status_code";
protected void applyStatusCodeIfPossible(HttpServletRequest request,
HttpServletResponse response, int statusCode) {
if (!WebUtils.isIncludeRequest(request)) {
response.setStatus(statusCode);
request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, statusCode);
}
}
4.返回错误页面
protected ModelAndView getModelAndView(String viewName, Exception ex,
HttpServletRequest request) {
return getModelAndView(viewName, ex);
}
protected ModelAndView getModelAndView(String viewName, Exception ex) {
ModelAndView mv = new ModelAndView(viewName);
if (this.exceptionAttribute != null) {
mv.addObject(this.exceptionAttribute, ex);
}
return mv;
}
实例探究
下面来看 springmvc 中常见的统一异常处理方法。
1.实现 HandlerExceptionResolver 接口
-
首先需要实现 HandlerExceptionResolver 接口。
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView("error");
return modelAndView;
}
}
-
配置到 Spring 配置文件中,或者加上@Component 注解。
<bean class="com.resolver.MyExceptionResolver"/>
2.添加 @ExceptionHandler 注解
首先来看它的注解定义:
Target(ElementType.METHOD)
Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
Class<? extends Throwable>[] value() default {};
}
在控制器中使用,可以定义不同方法来处理不同类型的异常。
public abstract class BaseController {
@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(HttpServletRequest request, HttpServletResponse response, Exception e) {
ModelAndView modelAndView = new ModelAndView("error");
return modelAndView;
}
@ExceptionHandler(NullPointerException.class)
public ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Exception e) {
ModelAndView modelAndView = new ModelAndView("error");
return modelAndView;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
使用 @ExceptionHandler 注解实现异常处理有个缺陷就是只对该注解所在的控制器有效。
想要让所有的所有的控制器都生效,就要通过继承来实现。
如上所示(定义了一个抽象的基类控制器) ,可以让其他控制器继承它实现异常处理。
public class HelloController extends BaseController
3.利用 SimpleMappingExceptionResolver 类
该类实现了 HandlerExceptionResolver 接口,是 springmvc 默认实现的类,通过它可以实现灵活的异常处理。
只需要在 xml 文件中进行如下配置:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="NullPointerException">nullpointpage</prop>
<prop key="IOException">iopage</prop>
<prop key="NumberFormatException">numberpage</prop>
</props>
</property>
<property name="statusCodes">
<props>
<prop key="nullpointpage">400</prop>
<prop key="iopage">500</prop>
</props>
</property>
<property name="defaultErrorView" value="errorpage"/>
<property name="defaultStatusCode" value="404"/>
</bean>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
-
exceptionMappings:定义 springmvc 要处理的异常类型和对应的错误页面;
-
statusCodes:定义错误页面和response 中要返回的错误状态码
-
defaultErrorView:定义默认错误显示页面,表示处理不了的异常都显示该页面。在这里表示 springmvc 处理不了的异常都跳转到 errorpage页面。
-
defaultStatusCode:定义 response 默认返回的错误状态码,表示错误页面未定义对应的错误状态码时返回该值;在这里表示跳转到 errorpage、numberpage 页面的 reponse 状态码为 404。
4.ajax 异常处理
对于页面 ajax 的请求产生的异常不就适合跳转到错误页面,而是应该是将异常信息显示在请求回应的结果中。
实现方式也很简单,需要继承了 SimpleMappingExceptionResolver ,重写它的异常处理流程(下面会详细分析)。
public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
if ((request.getHeader("accept").indexOf("application/json") > -1 ||
(request.getHeader("X-Requested-With") != null &&
request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))){
try {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write(ex.getMessage());
writer.flush();
writer.close();
} catch (Exception e) {
LogHelper.info(e);
}
return null;
}
return super.doResolveException(request, response, handler, ex);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
配置文件如上,只是将注入的 Bean 替换成我们自己的定义的 CustomSimpleMappingExceptionResolver 。