赞
踩
在SpringBoot中,常用的异常处理有两种:一种是 BasicErrorController,另一种是 @ControllerAdvice。BasicErrorController 用于处理非Controller抛出的异常,而@ControllerAdvice 用于处理Controller抛出的异常,对于非Controller抛出的异常它是不会管的。但是,如果是Controller层调用Service层,从Service层抛出,依然会抛到Controller,所以还是会调用@ControllerAdvice进行处理。
ControllerAdvice:异常处理异常处理
SpringBoot 默认的处理异常的机制是通过 BasicErrorController 类来实现的。当程序中出现异常时,SpringBoot 会向 /error 的 URL 发送请求。BasicErrorController 负责处理这个请求,并根据异常类型跳转到相应的页面来展示异常信息。

在 SpringBoot 中,可以通过配置自定义的错误页面来覆盖默认的错误页面。
首先,我们需要创建自定义的错误页面。在src/main/resources/templates/error目录下,创建HTML文件,例如对于error错误,创建error.html。
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>自定义错误页面</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- background-color: #f0f0f0;
- text-align: center;
- padding: 50px;
- }
- h1 {
- font-size: 48px;
- color: #333;
- }
- p {
- font-size: 24px;
- color: #666;
- }
- a {
- display: inline-block;
- padding: 10px 20px;
- background-color: #007bff;
- color: #fff;
- text-decoration: none;
- border-radius: 5px;
- }
- </style>
- </head>
- <body>
- <h1>发生错误!</h1>
- <p>请稍后重试或联系管理员。</p>
- <span th:text="${msg}"></span>
- </body>
- </html>
页面使用到了 thymeleaf
导包
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
GlobalException:(普通的处理请求)
- @Component
- public class GlobalException implements HandlerExceptionResolver {
-
- @Override
- public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
- ModelAndView modelAndView = new ModelAndView();
- // if (e instanceof NullPointerException){
- // modelAndView.setViewName("error");
- // }
- modelAndView.setViewName("error");
- modelAndView.addObject("msg",e.toString());
- return modelAndView;
- }
- }
AjaxGlobalException:(ajax的请求方式,返回的使json数据)
- public class AjaxGlobalException {
-
- @ResponseBody
- @ExceptionHandler
- public Map errorHandler(Exception e) {
-
- Map<String, Object> m = new HashMap<>();
- m.put("status", 500);
- m.put("msg", e.toString());
-
- return m;
- }
- }
- @RestController
- public class ErrorController {
-
- @GetMapping("/showList")
- public String showList() {
- int i = 1/0;
- return "showList";
- }
- @GetMapping("/showAll")
- public String showAll() {
- return "showAll";
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。