SpringBoot: 11.异常处理方式1(自定义异常页面)(转)

 

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

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

自定义错误页面

复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义错误页面</title>
</head>
<body>
    页面出错了。。。请与管理员联系
    <span th:text="${message}"></span>  <!--发生错误的信息-->
    <span th:text="${error}"></span>
</body>
</html>
复制代码

编写controller

复制代码
package com.bjsxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Administrator on 2019/2/12.
 */
@Controller
public class IndexController {


    @RequestMapping("toIndex")
    public String toIndex(){
        String str=null;
        str.length();
        return "index";
    }

    @RequestMapping("toIndex2")
    public String toIndex2(){
        int num=10/0;
        return "index";
    }

}
复制代码

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

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

自定义错误页面

复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义错误页面</title>
</head>
<body>
    页面出错了。。。请与管理员联系
    <span th:text="${message}"></span>  <!--发生错误的信息-->
    <span th:text="${error}"></span>
</body>
</html>
复制代码

编写controller

复制代码
package com.bjsxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Administrator on 2019/2/12.
 */
@Controller
public class IndexController {


    @RequestMapping("toIndex")
    public String toIndex(){
        String str=null;
        str.length();
        return "index";
    }

    @RequestMapping("toIndex2")
    public String toIndex2(){
        int num=10/0;
        return "index";
    }

}
复制代码

猜你喜欢

转载自www.cnblogs.com/kuangzhisen/p/10427170.html