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"/>
  • 相关阅读:
    SpringBoot启动过程中,候选类的过滤和加载
    Dubbo发布过程中,扩展点的加载
    Dubbo发布过程中,服务发布的实现
    Dubbo发布过程中,服务端调用过程
    SpringBean加载过程中,循环依赖的问题(一)
    Dubbo发布过程中,消费者的初始化过程
    DiscuzQ构建/发布小程序与H5前端
    Delphi写COM+的心得体会
    DBGridEh导出Excel等格式文件
    数据库直接通过bcp导出xml文件
  • 原文地址:https://www.cnblogs.com/j9527/p/12041052.html
Copyright © 2011-2022 走看看