栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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




    
    Title


    

这是自定义404

5xx.html




    
    Title


这是自定义5xx

3.运行测试

测试404

测试500

使用postman测试

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号