13.1、环境搭建
创建名为spring_mvc_exception的新module,过程参考9.1节和9.5节
13.1.1、创建错误提示页
 - <!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、创建会发生异常的控制器方法
 - 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、基本配置示例
 -
- <bean >
-
- <property name="exceptionMappings">
- <props>
-
- <property name="exceptionAttribute" value="exceptionMessage"></property>
-
- <property name="exceptionAttribute" value="exceptionMessage"></property><prop key="java.lang.ArithmeticException">errorPage</prop>
- </props>
- </property>
- </bean>
复制代码 13.3.2、基本示例测试效果


13.3.3、进阶配置示例
 -
- <property name="exceptionAttribute" value="exceptionMessage"></property>
复制代码 - 异常信息:<p th:text="${exceptionMessage}"></p>
复制代码 13.3.4、进阶示例测试效果


13.4、使用注解配置异常处理器
13.4.1、创建异常处理组件
 - 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、测试效果


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |