zoukankan      html  css  js  c++  java
  • SpringMvc 异常处理器

    简介

      SpringMvc 在处理请求过程中出现异常信息由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

    异常理解

      异常包含编译时异常运行时异常,其中编译时异常也叫预期异常。运行时异常只有在项目运行的情况下才会发现,编译的时候不需要关心。

      运行时异常,比如:空指针异常、数组越界异常,对于这样的异常,只能通过程序员丰富的经验来解决和测试人员不断的严格测试来解决。

      编译时异常,比如:数据库异常、文件读取异常、自定义异常等。对于这样的异常,必须使用 try catch代码块或者throws关键字来处理异常。

    异常处理思路

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

      系统的dao、service、controller出现都通过throws Exception向上抛出,最后由SpringMvc前端控制器交给异常处理器进行异常处理,如下图:

     全局范围只有一个异常处理器。

    自定义异常类

    第一步:CustomException.java

    package com.cyb.ssm.exception;
    
    /**
     * 自定义编译时异常
     * 
     * @author apple
     *
     */
    public class CustomException extends Exception {
        private String msg;
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public CustomException(String msg) {
            super();
            this.msg = msg;
        }
    }

    第二步:CustomExceptionResolver.java(重点)

    package com.cyb.ssm.resolver;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.cyb.ssm.exception.CustomException;
    
    public class CustomExceptionResolver implements HandlerExceptionResolver {
    
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) {
            String message="";
            // 异常处理逻辑
            if (ex instanceof CustomException) {
                message = ((CustomException) ex).getMsg();
            } else {
                message="未知错误";
            }
            ModelAndView mv=new ModelAndView();
            mv.setViewName("error");
            mv.addObject("message", message);
            return mv;
        }
    }

    第三步:在springmvc.xml中加入bean

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- 处理器类的扫描 -->
        <context:component-scan
            base-package="com.cyb.ssm.controller"></context:component-scan>
        <mvc:annotation-driven conversion-service="conversionService"/>
        <!-- 显示配置视图解析器 -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        <!-- 配置自定义的转换服务 -->
        <bean id="conversionService"
            class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <!-- 自定义日期类型转换器 -->
                    <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean>
                </set>
            </property>
        </bean>
        <!-- 配置异常处理器 -->
        <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean>
    </beans>

    第四步:jsp错误页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>错误页面</title>
    </head>
    <body>
        ${message }
    </body>
    </html>

    第五步:测试类

        @RequestMapping("queryItem")
        public ModelAndView queryItem() throws CustomException {
            //查询数据库,用静态数据模拟
            List<Item> itemList = Service.queryItemList();
            ModelAndView mvAndView = new ModelAndView();
            mvAndView.addObject("itemList", itemList);
            //设置视图(逻辑路径)
            mvAndView.setViewName("item/item-list");
            if (true) {
                throw new CustomException("我是自定义异常类");
            }
            return mvAndView;
        }

    实现

    源码 

    完整代码:直接下载

  • 相关阅读:
    事件总线Guava EventBus
    DDD—实体和值对象
    DDD—子域和限界上下文
    DDD—什么是领域驱动设计
    DDD—微服务,中台建设为什么需要领域驱动设计
    RabbitMQ 中的 7 种队列模式
    10w 行级别数据的 Excel 导入优化记录
    Java 反射是什么?
    21 条常用 Linux 命令
    一个 java 文件的执行过程
  • 原文地址:https://www.cnblogs.com/chenyanbin/p/12022180.html
Copyright © 2011-2022 走看看