1. 默认的错误页面

Spring Boot 默认提供了程序出错的结果映射路径/error
spring-boot-autoconfigure.jar/org.springframework.boot.autoconfigure.web.BasicErrorController.java

其中,errorHtml方法是用于处理浏览器端的请求,它返回一个简单的错误页面。而error方法是用于处理客户端的调用,它返回一个简单的 JSON 字串信息。

当请求发生错误,它会响应浏览器一个简单的页面来描述这些错误信息,如 404 错误页面:

2. 自定义错误页面

Spring Boot 默认是到模板文件所在目录的error文件夹中查找错误码对应的视图模板文件:
spring-boot-autoconfigure-1.5.2.RELEASE.jar/org.springframework.boot.autoconfigure.web.DefaultErrorViewResolver.java

因此,自定义的错误模板文件放在 error 目录下即可。如:

# src/main/resources/templates/error/404.html(Thymeleaf)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>404错误页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>404</h1>
<p th:text="|timestamp:${#dates.format(timestamp, 'yyyy-MM-dd HH:mm:ss:SSS')}|"></p>
<p th:text="|status:${status}|"></p>
<p th:text="|error:${error}|"></p>
<p th:text="|message:${message}|"></p>
<p th:text="|path:${path}|"></p>
</body>
</html>

最终的效果:

示例项目开发环境:Java-8、Maven-3、IntelliJ IDEA-2017、Spring Boot-1.5.2.RELEASE
完整示例项目链接:spring-boot-error-page-sample
参考文档文献链接:http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-error-handling-custom-error-pages