Springboot全局异常处理

1、全局异常处理,指的是对于程序中产生的Exception进行的处理。产生了异常之后,可以统一跳转到一个页面进行错误提示,也可以通过Restful形式返回错误信息。

  注意:关于全局错误与全局异常的区别。全局错误,指的是对http状态码进行的错误跳转处理,全局异常指的是发生某些异常(如果处理的是Exception,则表示处理全部异常)之后的跳转页面。两者属于并行的概念,在项目开发中建议同时配置两者。

2、首先,创建一个全局异常处理,该类可以处理所有的Exception异常。

 1 package com.demo.config;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.springframework.web.bind.annotation.ControllerAdvice;
 6 import org.springframework.web.bind.annotation.ExceptionHandler;
 7 import org.springframework.web.servlet.ModelAndView;
 8 
 9 /**
10  * 
11  * @author
12  * 
13  *         作为一个控制层的切面处理
14  *
15  */
16 @ControllerAdvice
17 public class GlobalExceptionAdvice {
18 
19     public static final String DEFAULT_ERROR_VIEW = "error"; // 错误显示页error.html
20 
21     /**
22      * 出现异常会执行此方法
23      * 
24      * @param request
25      * @param e
26      * @return
27      */
28     @ExceptionHandler(Exception.class)
29     public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
30         // 设置跳转路径
31         ModelAndView mav = new ModelAndView(GlobalExceptionAdvice.DEFAULT_ERROR_VIEW);
32         // 保存异常信息
33         mav.addObject("exception", e);
34         // 获取请求的路径
35         mav.addObject("url", request.getRequestURL());
36         return mav;
37     }
38 
39 }

然后在src/main/view/templates下面创建error.html页面,进行错误信息显示,注意,必须将error.html页面创建到src/main/view/templates下面的,不然无法进行跳转显示的。

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.thymeleaf.org"></html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8     <h1>搞事情啊!!!</h1>
 9     
10     <!-- 输出url属性 -->
11     <p th:text="${url}"></p>
12     <p th:text="${exception}"></p>
13 
14 </body>
15 </html>

创建一个控制器,主要作用是产生一个异常信息,以观察全局异常处理是否生效。

 1 package com.demo.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.ResponseBody;
 6 
 7 @Controller
 8 public class SpringBootController {
 9 
10     @RequestMapping(value = "/world")
11     @ResponseBody
12     public String hello() {
13         int result = 1 / 0;
14         System.out.println("hello world!!!");
15         return "error404";
16     }
17 
18 }

只要访问http://127.0.0.1:8081/world路径,就会产生异常,而产生异常之后将统一跳转到error.html页面。

项目结构,如下所示:

切记:SpringBoot项目中Thymeleaf的动态页面需要保存在templates(src/main/resources/templates)目录中,页面的扩展名默认使用的是*.html,如果开发者觉得这样的设计不合理,也可以通过application.yml配置文件自行修改。

  Thyemeleaf静态资源,在进行Web信息显示的过程中,除了可以配置动态显示页面之外,也可以配置静态资源(如*.html、*.css、*.js等)。对于静态资源,要求其必须放在源文件夹的static(src/main/resources/static)目录中。

3、可以设计为基于Restful错误信息提示。在发生异常之后采用跳转的形式来处理,而SpringBoot最大的特点是支持Restful处理,因此为了描述异常,也可以直接采用Restful的形式回应异常信息,即不再跳转到HTML页面进行显示。

 1 package com.demo.config;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.springframework.http.HttpStatus;
 6 import org.springframework.web.bind.annotation.ExceptionHandler;
 7 import org.springframework.web.bind.annotation.RestControllerAdvice;
 8 
 9 /**
10  * 
11  * @author
12  * 
13  *         作为一个控制层的切面处理
14  *
15  */
16 @RestControllerAdvice // 使用restful风格进行返回
17 public class GlobalExceptionAdvice {
18 
19     public static final String DEFAULT_ERROR_VIEW = "error"; // 错误显示页error.html
20 
21     /**
22      * 出现异常会执行此方法
23      * 
24      * @param request
25      * @param e
26      * @return
27      */
28     @ExceptionHandler(Exception.class) // 处理所有异常
29     public Object defaultErrorHandler(HttpServletRequest request, Exception e) {
30         // 搞一个内部类
31         class ErrorInfo {
32             private Integer code;
33             private String message;
34             private String url;
35 
36             public Integer getCode() {
37                 return code;
38             }
39 
40             public void setCode(Integer code) {
41                 this.code = code;
42             }
43 
44             public String getMessage() {
45                 return message;
46             }
47 
48             public void setMessage(String message) {
49                 this.message = message;
50             }
51 
52             public String getUrl() {
53                 return url;
54             }
55 
56             public void setUrl(String url) {
57                 this.url = url;
58             }
59 
60         }
61 
62         ErrorInfo errorInfo = new ErrorInfo();
63         errorInfo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); // 状态码
64         errorInfo.setMessage(e.getMessage()); // 保存错误信息
65         errorInfo.setUrl(request.getRequestURI().toString()); // 保存错误路径
66         return errorInfo;
67     }
68 
69 }

如果使用@RestControllerAdvice注解,则此时的异常处理将使用Restful风格,程序发生异常之后的运行效果,如下所示:

原文地址:https://www.cnblogs.com/biehongli/p/13959734.html