SpringBoot默认的处理异常的机制:

SpringBoot 默认的已经提供了一套处理异常的机制。一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 springBoot 中提供了一个叫 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息

spring boot 错误日志 spring boot错误处理_错误页面


如 果我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 再src/main/resources/templates 目录下创建 error.html 页面。注意:名称必须叫 error.

SpringBoot处理异常方式一:自定义错误页面

@RequestMapping("hello")
    public String hello(){
        int i = 10 / 0;
        return "success";
    }

    @RequestMapping("show1")
    public String show1(){
        String str = null;
        System.out.println(str.length());
        return "success";
    }
错误页面展示:
    <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>
	页面出错了
	<span th:text="${error}"></span>
</body>
</html>

SpringBoot处理异常方式一:下标索引越界

@RequestMapping("show2")
    public String show2(){
        int[] arr = new int[3];
        arr[100] = 90;
        return "success";
    }

@ControllerAdvice //标识当前类是一个全局异常处理类

@ControllerAdvice+@ExceptionHandler 注解处理异常

上一种方式必须要在每一个Controler里面重复写异常处理代码,代码复用性太差,这一种方法可以实现异常的全局处理。需要创建一个能够处理异常的全局异常类。在该类上需要添加@ControllerAdvice 注解

spring boot 错误日志 spring boot错误处理_异常处理_02

处理思路

spring boot 错误日志 spring boot错误处理_异常处理_03