SpringMVC 异常处理 - HandlerExceptionResolver

基本概念

在 SpringMVC 中 HandlerExceptionResolver 接口负责统一异常处理。

内部构造

下面来看它的源码:

public interface HandlerExceptionResolver {

    ModelAndView resolveException(
        HttpServletRequest request, HttpServletResponse response, 
        Object handler, Exception ex);
}

AbstractHandlerMethodExceptionResolver

该类是实现了 HandlerExceptionResolver 接口的抽象实现类。关键来看 resolveException 方法:

public ModelAndView resolveException(HttpServletRequest request, 
    HttpServletResponse response, Object handler, Exception ex) {

    // 1.判断是否支持该处理器
    if (shouldApplyTo(request, handler)) {

        // 省略部分源码...

        // 2.预处理响应消息,让请求头取消缓存
        prepareResponse(ex, response);

        // 3.异常处理,空方法
        ModelAndView mav = doResolveException(request, response, handler, ex);
        if (mav != null) {
            logException(ex, request);
        }

        return mav;

    } else {
        return null;
    }
}

接着来看 shouldApplyTo 方法:

protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
    if (handler != null) {
        // 分别比对 mappedHandlers 、mappedHandlerClasses 
        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);
}

SimpleMappingExceptionResolver

它继承了 AbstractHandlerMethodExceptionResolver 。实现了真正的异常处理。

来看该类的 doResolveException 方法:

protected ModelAndView doResolveException(HttpServletRequest request, 
    HttpServletResponse response, Object handler, Exception ex) {

    // 1.决定的视图
    String viewName = determineViewName(ex, request);

    if (viewName != null) {
        // 2.决定错误状态码
        Integer statusCode = determineStatusCode(request, viewName);
        if (statusCode != null) {
            3.设置错误状态码
            applyStatusCodeIfPossible(request, response, statusCode);
        }

        // 4.返回错误页面
        return getModelAndView(viewName, ex, request);
    } else {
        return null;
    }
}

1.决定视图

// 被过滤的异常集合
private Class<?>[] excludedExceptions;

// 被处理的异常集合
private Properties exceptionMappings;

// 默认的错误显示页面
private String defaultErrorView;

protected String determineViewName(Exception ex, HttpServletRequest request) {

    String viewName = null;

    // 1.判断属于被过滤的异常?
    if (this.excludedExceptions != null) {
        for (Class<?> excludedEx : this.excludedExceptions) {
            if (excludedEx.equals(ex.getClass())) {
                return null;
            }
        }
    }

    // 2.判断属于被处理的异常?
    if (this.exceptionMappings != null) {
        // 找到匹配的页面
        viewName = findMatchingViewName(this.exceptionMappings, ex);
    }

    // 3.为空则使用默认的错误页面
    if (viewName == null && this.defaultErrorView != null) {
        viewName = this.defaultErrorView;
    }
    return viewName;
}

接着来看 findMatchingViewName 方法:

protected String findMatchingViewName(Properties exceptionMappings, Exception ex) {
    String viewName = null;
    String dominantMapping = null;
    int deepest = Integer.MAX_VALUE;

    // 遍历 exceptionMappings
    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;
}

继续来看 getDepth 方法:

protected int getDepth(String exceptionMapping, Exception ex) {
    // 匹配返回 0,不匹配返回 -1 ,depth 越低的好
    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)) {
        // 省略代码...

        // 设置错误状态码,并添加到 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 {
    // 处理 IO 异常
    @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;
    }
}

使用 @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>

-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) {

        // 判断是否 Ajax 请求 
         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);
    }
}

配置文件如上,只是将注入的 Bean 替换成我们自己的定义的 CustomSimpleMappingExceptionResolver 。

转载于:https://my.oschina.net/crazybird/blog/866380

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值