14.SpringMVC 异常处理 - HandlerExceptionResolver

基本概念

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


内部构造

下面来看它的源码:

public interface HandlerExceptionResolver {

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

再来看它的继承关系:

Alt text


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


  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
[ 2021年,将Spring全家桶的课程进行Review,确保不再有顺序错乱等问题导致学员看不懂内容,进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始逐步增加高阶的Spring Security等内容,课件将逐步进行上传,敬请期待! ]本课程是Spring全家桶案例精讲课程的第二部分Spring MVC,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Java Spring的Web知识点,主要是关于Spring MVC的应用,包含:表单的增删改查、国际化、过滤器、拦截器、日志Log4j2及slf4j的使用、主题更改网站皮肤及样式、文件上传等的案例讲解,并且最后以一个SSM(Spring+Spring MVC+Mybatis)贯穿前后台的案例作为Spring MVC课程的终奖, 从而使大家快速掌握Spring的基础核心知识,快速上手,为面试、工作等做好充足准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验 【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oxf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值