SpringBoot的错误处理

错误处理

关于错误处理,SpringBoot官网有这么一段话:

By default, Spring Boot provides an /error mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a “whitelabel” error view that renders the same data in HTML format (to customize it, add a View that resolves to error).

  1. 默认情况下,SpringBoot提供/error处理所有错误映射。
  2. 对于机器客户端,将生成一个JSON响应,其中包含错误、HTTP状态和异常消息的详细信息;对于浏览器客户端,将响应一个“whitelabel”错误视图,并以HTML格式呈现相同数据。

具体看个例子。
新建一个Spring项目:demo10,添加依赖:Spring Web、Spring Configuration Processor、Lombok和Thymeleaf。
com.example.boot下新建控制器:controller.IndexController。

package com.example.boot.controller;

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

@Controller
public class IndexController {
    @GetMapping("/divide")
    public String divide(){
        int i = 10/0;
        return "division";
    }
}

resources.templates下新建视图文件:index.html和devision.html。

<!-- index.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
<a th:href="@{/divide}">除法(500)</a><br/>
<a th:href="@{/multiply}">乘法(404)</a>
</body>
</html>
<!-- division.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>division</title>
</head>
<body>
<h1>除法</h1>
</body>
</html>

启动应用。
使用浏览器访问localhost:8080,点击链接分别访问接口:/divide和/multiple。
在这里插入图片描述
使用IDEA http访问接口:/divide和/multiple。
在这里插入图片描述

自定义错误页面

关于自定义错误页面,SpringBoot官网是这么说的:
在这里插入图片描述

所以,在templates下新建目录:error,error目录下新建视图文件:404.html和5xx.html。

<!-- 404.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
<h1>Error: 404, Not Found</h1>
</body>
</html>
<!-- 5xx.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>5xx</title>
</head>
<body>
<h1>Error: 500, Internal Server Error</h1>
</body>
</html>

重启应用,测试效果。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值