前言
如果能将所有类型的异常处理从各层中解耦出来,则既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。幸运的是,Spring框架支持这样的实现。接下来将从自定义error页面。@ExceptionHandler注解以及@ControllerAdvice3种方式讲解Spring Boot应用的异常统一处理
具体处理步骤如下:
自定义error页面
在Spring Boot Web应用的src/main/resources/templates 目录下添加error.html页面 访问发生错误或异常时,Spring Boot将自动找到该页面作为错误页面。Spring Boot为错误页面提供了以下属性
- timestamp 错误发生时间
- status HTTP状态码
- error 错误原因
- exception 异常的类名
- message 异常消息
- errors BindingResult异常里的各种错误
- trace 异常跟踪信息
- path 错误发生时请求的URL路径
1: 创建名为com.ch.ch5_3.exception的包 并在该包中创建名为MyException 具体代码如下
1 2 3 4 5 6 7 8 9 10 | package com.ch.ch5_3.exception; public class MyException extends Exception { private static final long serialVersionUID = 1L; public MyException() { super (); } public MyException(String message) { super (message); } } |
2:创建控制器类TestHandleExceptionController
创建名为com.ch,ch5_3.controller的包 并在该包中创建名为TestHandleExceptionController的控制器类,在该控制器类中,在4个请求处理方法,一个是导航到index.html 另外三个分别抛出不同的异常 部分代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.ch.ch5_3.controller; import java.sql.SQLException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; public void db() throws SQLException { throw new SQLException( "数据库异常" ); } @RequestMapping ( "/my" ) public void my() throws MyException { throw new MyException( "自定义异常" ); } @RequestMapping ( "/no" ) public void no() throws Exception { throw new Exception( "未知异常" ); } } |
3:View视图页面
Thymeleaf模板默认将视图页面放在src/main/resources/templates目录下。因此我们在src/main/resources/templates 目录下新建html页面文件,index.html和error.html
在index.html页面中 有4个超链接请求,3个请求在控制器中有对应处理,另一个请求是404错误
部分代码如下
1 2 3 | < title >index</ title >< a rel = "external nofollow" >处理数据库异常</ a >< br >< a rel = "external nofollow" >处理自定义异常</ a >< br >< a rel = "external nofollow" >处理未知错误</ a > < hr >< a rel = "external nofollow" >404错误</ a > |