错误处理机制
# 410.错误处理机制
来讲讲异常处理机制
# 官网文档
大意:默认情况下,Spring Boot提供/error
处理所有错误的映射。
对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。
对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
# 默认错误页面
比如,我们登录后,访问一个不存在的页面:
如果我们使用Postman(记得带上Cookie,可以从浏览器的控制台中获取):
访问:返回的是JSON数据
# 自定义404异常页面
官网文档:
Custom Error Pages
If you want to display a custom HTML error page for a given status code, you can add a file to an /error directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or be built by using templates. The name of the file should be the exact status code or a series mask.
For example, to map 404 to a static HTML file, your directory structure would be as follows:
src/ +- main/ +- java/ | + <source code> +- resources/ +- public/ +- error/ | +- 404.html +- <other public assets>
1
2
3
4
5
6
7
8
9To map all 5xx errors by using a FreeMarker template, your directory structure would be as follows:
src/ +- main/ +- java/ | + <source code> +- resources/ +- templates/ +- error/ | +- 5xx.ftlh +- <other templates>
1
2
3
4
5
6
7
8
9
大意:我们可以将一些错误页面,放到public/error目录下;如果是动态页面,也可以放到模板引擎的目录(templates/error)。
我们在templates目录下,新建error目录;然后将《前端资源文件demo》中的500.html,404.html复制到error目录。
为了方便,我们可以将500.html重命名为5xx.html,这样所有5开头的错误页面,都会跳转到该页面:
我们重启,然后访问一个不存在的路径,就是我们自定义的错误页面了:
注意,顺便修改下404页面的 "Back to Home"按钮的超链接:
<a class="back-btn" th:href="@{/main.html}"> Back To Home</a>
# 自定义5xx异常页面
我们手工制造一个异常:
public class TableController {
@GetMapping("/basic_table")
public String basic_table(){
int i = 10 / 0;
return "table/basic_table";
}
//.........
}
2
3
4
5
6
7
8
9
然后重启,访问,可以看到有正常跳转:
我们还可以取出异常信息(例如JSON里的message和trace,堆栈信息),展示到页面上:
<section>
<div class="container ">
<section class="error-wrapper text-center">
<h1><img alt="" src="images/500-error.png"></h1>
<h2>OOOPS!!!</h2>
<h3 th:text="${message}">Something went wrong.</h3>
<p class="nrml-txt" th:text="${trace}">Why not try refreshing you page? Or you can <a href="#">contact our support</a> if the problem persists.</p>
<a class="back-btn" href="index.html"> Back To Home</a>
</section>
</div>
</section>
2
3
4
5
6
7
8
9
10
11
12
13
然后重启,可以看到有打印:
# 源码
已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo6,读者可以通过切换分支来查看本文的示例代码