错误处理
关于错误处理,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).
- 默认情况下,SpringBoot提供/error处理所有错误映射。
- 对于机器客户端,将生成一个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>
重启应用,测试效果。