广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot详解实现自定义异常处理页面方法
  • 398
分享到

SpringBoot详解实现自定义异常处理页面方法

2024-04-02 19:04:59 398人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.相关介绍2.代码实现3.运行测试1.相关介绍 当发生异常时, 跳转到我们自定义的异常处理页面. SpringBoot中只需在静态资源目录下创建一个error文件夹, 并把异常

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)获取并写入自定义的异常处理页面中

到此这篇关于SpringBoot详解实现自定义异常处理页面方法的文章就介绍到这了,更多相关SpringBoot异常处理内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot详解实现自定义异常处理页面方法

本文链接: https://www.lsjlt.com/news/152694.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作