13.1、环境搭建

创建名为spring_mvc_exception的新module,过程参考9.1节和9.5节

13.1.1、创建错误提示页

image

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>错误页面</title>
</head>
<body>

<h1>errorPage.html</h1>

</body>
</html>

13.1.2、创建会发生异常的控制器方法

image

package online.liaojy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author liaojy
 * @date 2023/11/13 - 19:48
 */
@Controller
public class TestController {

    @RequestMapping("/test/hello")
    public String testHello(){
        // 在控制器方法中,制造一个数值运算异常
        System.out.println(1/0);
        return "success";
    }

}

13.2、异常处理器概述

  • SpringMVC 提供了一个处理控制器方法执行异常的接口:HandlerExceptionResolver

  • HandlerExceptionResolver 接口的实现类有:DefaultHandlerExceptionResolver 和 SimpleMappingExceptionResolver

  • 实际工作中,有时使用 SimpleMappingExceptionResolver 异常处理器,来对控制器方法出现的异常进行自定义异常处理

13.3、使用xml配置异常处理器

13.3.1、基本配置示例

image

    <!--配置异常处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--设置异常和错误提示页面的映射关系-->
        <property name="exceptionMappings">
            <props>
                <!--
                    属性key:用来设置要处理的(在控制器方法执行过程中可能出现的)异常的全类名
                    <prop>标签体:用来设置当(控制器方法执行)发生异常时,要跳转到的逻辑视图
                -->
                <prop key="java.lang.ArithmeticException">errorPage</prop>
            </props>
        </property>
    </bean>

13.3.2、基本示例测试效果

image

image

13.3.3、进阶配置示例

image

        <!--属性value:设置共享到域对象中的异常信息的属性名-->
        <property name="exceptionAttribute" value="exceptionMessage"></property>

image

异常信息:<p th:text="${exceptionMessage}"></p>

13.3.4、进阶示例测试效果

image

image

13.4、使用注解配置异常处理器

13.4.1、创建异常处理组件

image

package online.liaojy.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author liaojy
 * @date 2023/11/13 - 20:42
 */
// @ControllerAdvice 注解:用于将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {

    // @ExceptionHandler 注解:用来设置(该方法)要处理的异常
    @ExceptionHandler(ArithmeticException.class)
    public String testHandleException(Throwable ex,Model model){

        // 设置共享到请求域中的异常信息的属性名
        model.addAttribute("exceptionMessage",ex);

        // 返回发生异常时的逻辑视图
        return "errorPage";
    }

}

13.4.2、测试效果

image

image