首页 > 其他分享 >SpringBoot 统一页面异常处理

SpringBoot 统一页面异常处理

时间:2023-03-19 11:05:12浏览次数:44  
标签:code SpringBoot ModelAndViewException CustomException msg ModelAndView 异常 public

相关博客:<a rel="nofollow" href="https://hcshow.blog.csdn.net/article/details/103081763">SpringBoot 统一异常处理</a>

第一步:创建项目

添加Maven依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 集成thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

application.yml

server:
    port: 80
    servlet:
        context-path: /wpe
spring:
    thymeleaf:
        #前缀,也就是模板存放的路径
        prefix: classpath:/templates/
        #编码格式
        encoding: UTF-8
        check-template-location: false
        #关闭缓存,不然无法看到实时页面
        cache: false
        #后缀
        suffix: .html
        #设置不严格的html
        mode: HTML
        servlet:
            content-type: text/html

第二步:自定义异常

CustomException.java:

public class CustomException extends RuntimeException {
    // 异常错误编码
    private Integer code;
    // 异常信息
    private String msg;
    private CustomException() {
    }
    public CustomException(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}

ModelAndViewException.java

public class ModelAndViewException extends RuntimeException {
    // 异常错误编码
    private Integer code;
    // 异常信息
    private String msg;
    private ModelAndViewException() {
    }
    public static ModelAndViewException transfer(CustomException e) {
        return new ModelAndViewException(e.getCode(), e.getMessage());
    }
    private ModelAndViewException(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}

第三步:自定义异常处理器

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(ModelAndViewException.class)
    public ModelAndView viewExceptionHandler(HttpServletRequest req, ModelAndViewException e) {
        ModelAndView modelAndView = new ModelAndView();
        //将异常信息设置如modelAndView
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", req.getRequestURL());
        modelAndView.setViewName("error");
        //返回ModelAndView
        return modelAndView;
    }
}

第四步:自定义注解及处理器

注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ModelAndView {
}

注解处理器

@Aspect
@Component
public class ModelViewAspect {
    //设置切入点:这里直接拦截被@ModelView注解的方法
    @Pointcut("@annotation(com.hc.anno.ModelAndView)")
    public void pointcut() { }

    /**
     * 当有ModelAndView的注解的方法抛出异常的时候,做如下的处理
     */
    @AfterThrowing(pointcut="pointcut()",throwing="e")
    public void afterThrowable(Throwable e) {
        if(e instanceof CustomException){
            throw ModelAndViewException.transfer((CustomException) e);
        }
    }
}

第五步:创建Controller

@Controller
@RequestMapping("/mave")
@Slf4j
public class ModelAndViewExceptionController {
    /**
     * 模拟系统异常
     */
    @ModelAndView
    @GetMapping("/fun1")
    public String fun1() {
        try {
            Class.forName("com.mysql.jdbc.xxxx.Driver");
        } catch (ClassNotFoundException e) {
            throw new CustomException(400,"在XXX业务,ff1()方法内,出现ClassNotFoundException");
        }
        return "index";
    }
}

第六步:在resources/templates目录下创建error.html

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

        <div th:text="${exception}"></div>
        <div th:text="${url}"></div>
    </body>
</html>

第七步:启动项目,结果:

在这里插入图片描述

标签:code,SpringBoot,ModelAndViewException,CustomException,msg,ModelAndView,异常,public
From: https://blog.51cto.com/lianghecai/6130994

相关文章