SpringBoot之SpringBoot整合全局捕获异常

SpringBoot之SpringBoot整合全局捕获异常

概念:

  为什么需要添加全局捕获异常呢?因为系统在运行时很多时候会因为不确定的因素会出现异常,会将错误直接显示到页面上,当然这对于开发人员看来是很好的,但是对于用户来说,你给我报一大堆错误?你不想干了吧,其实现在我们公司也是这样干的,我居然不知道,所以学无止境,加油吧,不过这个方案可以在下次开会的时候提一下【让我看看】

编写代码:

  在aspect包下面创建RuntimeExceptionHandler.java

package com.springboot.demo.aspect;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author ZYGisComputer
 */
@ControllerAdvice
public class RuntimeExceptionHandler {

    /**
     * 拦截运行异常出现的错误
     *
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public String exceptionHandler() {
        return "error";
    }

}

编写等待报错的接口,写一个最简单的除以0的错误吧

@GetMapping("byZero")
    public Integer byZero(Integer i) {
        return 5 / i;
    }

在templates下写了一个error.html的页面,模板引擎采用的是thymeleaf,不知道则么用的看看我写的《SpringBoot之SpringBoot整合Thymeleaf模板引擎

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
</head>
<body>
    系统出现错误,请联系研发人员,锤他!
</body>
</html>

启动项目测试:

 成功拦截到错误,哈哈,以后就不用一直弹500了,他说也可以使用提示信息,但是我感觉页面应该会比提示信息好一些,对于用户更加直观一些

作者:彼岸舞

时间:2021126

内容关于:SpringBoot

本文来源于网络,只做技术分享,一概不负任何责任

原文地址:https://www.cnblogs.com/flower-dance/p/14331931.html