zoukankan      html  css  js  c++  java
  • SpringMVC框架(4)--异常处理

    异常处理的思路:

    系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。

    系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:

     

    有两种方式处理异常:

    ① 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

    简单异常处理器,是springmvc提前做好的处理器接口, 直接配置即可使用

    <!--配置简单映射异常处理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--默认错误视图-->
        <property name="defaultErrorView" value="forward:/error/errorMsg.jsp"/>       
        <property name="exceptionMappings">
            <map>
                <!--除零异常视图-->
                <entry key="ArithmeticException" value="forward:/error/arithmetic.jsp"/>  
                <!--类型转换异常视图-->
                <entry key="ClassCastException" value="forward:/error/classCast.jsp"/>       
            </map>
        </property>
    </bean>

    ② 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器

    定义一个类,实现HandlerExceptionResolver接口,重写方法

    public class MyExceptionResolver implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex) {
            //创建ModelAndView
            ModelAndView modelAndView = new ModelAndView();
            //判断出现的异常是什么异常
            if (ex instanceof ArithmeticException){     //如果是除零异常
                //跳转到"forward:/error/arithmetic.jsp"
                modelAndView.setViewName("forward:/error/arithmetic.jsp");
            }else if (ex instanceof ClassCastException){   //如果类型转换异常
                modelAndView.setViewName("forward:/error/classCast.jsp");
            }else{  //其他异常,就跳转到exceptionPage页面
                modelAndView.setViewName("forward:/error/exceptionPage.jsp");
            }
    
            return modelAndView;
        }
    }

    配置异常处理器

    <bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>
  • 相关阅读:
    指针和数组分析(上)
    函数对象分析
    C语言关键字
    STM32串口遇到的一个问题
    map文件分析
    对象的销毁
    对象的构造顺序
    JavaScript实现表单的校验以及匹配正则表达式
    Python Turtle库绘制表盘时钟
    Python Turtle库绘制蟒蛇
  • 原文地址:https://www.cnblogs.com/j9527/p/12041052.html
Copyright © 2011-2022 走看看