15-SpringBoot 自定义异常处理页面

1.相关介绍

  • 当发生异常时, 跳转到我们自定义的异常处理页面.

  • SpringBoot中只需在静态资源目录下创建一个error文件夹, 并把异常处理页面放入其中, 页面的命名与异常错误代码对应, 如404.html, 500.html.

  • 5xx.html可以对应所有错误代码为5开头的错误

  • 默认静态资源目录为类路径(resources)下的:

    /static
    /public
    /resources
    /META-INF/resources

2.代码实现

在这里插入图片描述

HelloController

package com.limi.springboottest2.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @ResponseBody
    @GetMapping("/test1")
    public String test1(){
        int i = 10/0; //模拟500异常
        return "ok";
    }
}

404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是自定义404</h1>
</body>
</html>

5xx.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>这是自定义5xx</h1>
</body>
</html>

3.运行测试

测试404
在这里插入图片描述
测试500
在这里插入图片描述
使用postman测试
在这里插入图片描述

{
    "timestamp": "2022-06-22T04:12:13.740+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "java.lang.ArithmeticException: / by zero\r\n\tat com.limi.springboottest2.controller.HelloController.test1(HelloController.java:14),
    "message": "/ by zero",
    "path": "/test1"
}

返回的信息我们可以使用模板引擎(如thymeleaf)获取并写入自定义的异常处理页面中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值