Spring Boot自定義錯誤視圖的方法詳解
Spring Boot缺省錯誤視圖解析器
Web應(yīng)用在處理請求的過程中發(fā)生錯誤是非常常見的情況,SpringBoot中為我們實現(xiàn)了一個錯誤視圖解析器(DefaultErrorViewResolver)。它基于一些常見的約定,嘗試根據(jù)HTTP錯誤狀態(tài)碼解析出錯誤處理視圖。它會在目錄/error下針對提供的HTTP錯誤狀態(tài)碼搜索模板或者靜態(tài)資源,比如,給定了HTTP狀態(tài)碼404,它會嘗試搜索如下模板或者靜態(tài)資源:
- /<templates>/error/404.<ext> - 這里<templates>表示所配置的模板所在目錄,<ext>表示所用的模板的文件名
- /<static>/error/404.html- 這里<static>表示靜態(tài)資源文件所在路徑、
- /<templates>/error/4xx.<ext>
- /<static>/error/4xx.html
如果找不到就用默認(rèn)的白標(biāo)錯誤視圖,如下圖所示:

因此,為了給用戶最佳的使用體驗,404等常見錯誤需要我們自定義頁面來處理。以下是幾種自定義錯誤頁面的方式。
方式1. 定義靜態(tài)的錯誤頁面
在 resources 下的 static 目錄下,新建 error 目錄,在其中新建各種靜態(tài)錯誤頁面,如 404、500,也可以模糊處理,如4xx、5xx 等,當(dāng)程序運行出錯時,會自動根據(jù)錯誤代碼(如500)找到相應(yīng)的錯誤頁面(如/static/error/500.html),給予展示。

方式2. 定義動態(tài)的錯誤頁面(有采用模板引擎)
在有使用模板的情況下,SpringBoot缺省的錯誤視圖解析器也會在/<templates>/error下搜索錯誤展示視圖。我們可以使用項目中的視圖模板引擎在錯誤頁面來定制展示我們的錯誤消息。
1) 在 resources 下的 templates 目錄下,新建 error 目錄,在其中新建各種靜態(tài)錯誤頁面,如 404、500,也可以模糊處理,如4xx、5xx等(與方式1一致)+

在模板引擎的支持下可以取到錯誤的一些信息,并定制化顯示在頁面上,如下(freemarker模板):

錯誤信息定制:
- timestamp:時間戳
- status:狀態(tài)碼
- error:錯誤提示
- exception:異常對象
- trace:跟蹤流程日志,404狀態(tài)下無
- message:異常消息
- path:請求路徑
方式3. 自定義實現(xiàn)錯誤視圖解析,統(tǒng)一錯誤處理
如果不想要使用缺省的錯誤處理視圖解析器,想要定制一些自己的東西(比如說:錯誤引導(dǎo)信息等),按照官方文檔的建議我們可以自定義實現(xiàn)錯誤視圖解析接口來處理。
下面就是通過實現(xiàn)錯誤視圖解析接口ErrorViewResolver,將4xx、5xx的錯誤頁面集中在一個自定義視圖上:
1)實現(xiàn) ErrorViewResolver 接口
package com.hongyang.admin.web;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 實現(xiàn)自定義的錯誤視圖解析器
*/
@Component
public class AdminErrorViewResolver implements ErrorViewResolver {
/**
* 實現(xiàn)ErrorViewResolver約定方法,
* 返回統(tǒng)一的錯誤視圖.
* @param request
* @param status
* @param model
* @return
*/
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
return new ModelAndView("/error/index", model);
}
}
2)完成錯誤視圖,在templates/error下添加index.ftlh視圖(freemarker模板)
<!DOCTYPE html>
<html>
<head >
<link href="/content/public/images/logo-small.png" rel="external nofollow" rel="shortcut icon" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${status}</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<style>
body {
position: fixed;
z-index: 10;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
padding: 0;
margin: 0px;
font-size: 14px;
background: #fff;
word-wrap: break-word;
}
p {
padding: 0 15px;
}
.btn {
border: 0px;
color: #fff;
cursor: pointer;
text-align: center;
background-color: #ff7a5f\0;
box-shadow: #cccccc 0 2px 15px 0;
-webkit-box-shadow: 0 2px 7px 0 rgba(0,0,0,0.2);
background: radial-gradient(circle at 300% 50%, rgb(255, 195, 114) 50%, rgb(255, 105, 90) 100%);
transition: all .2s ease-out,box-shadow .2s ease-out;
}
.btn:hover {
color: #FFFFFF;
transform: scale(1.1);
}
.btn:focus {
outline: none;
}
.container {
margin: 8% auto;
}
.container p {
margin: 35px auto;
text-align: center;
}
.container img {
width: 20%;
}
.container .font {
color: #848484;
}
.container .btn-back {
width: 180px;
height: 35px;
border-radius: 6px;
}
#container-info {
display: none;
position: fixed;
z-index: 11;
top: 5%;
left: 0;
right: 0;
margin: 0 auto;
width: 65%;
height: 85%;
overflow: hidden;
border-radius: 4px;
border: 1px solid #f1986e;
background-color: #fff;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgb(242, 154, 110);
}
#container-info .btn-close {
position: absolute;
right: 5px;
top: 5px;
width: 25px;
height: 25px;
line-height: 25px;
font-size: 22px;
padding: 2px;
border-radius: 50%;
text-align: center;
}
#container-info p {
font-size: 12px;
line-height: 20px;
}
.show {
display: block !important;
}
.cor-r {
color: red;
}
@media (max-width: 767px) {
.container img {
width: 50%;
}
#container-info {
width: 85%;
}
}
.panel-heading {
height: 32px;
line-height: 32px;
padding: 5px 15px;
}
.panel-body {
height: calc(85vh - 40px);
overflow: auto;
}
.panel-orange .panel-heading {
background-color: #ffa0681f;
color: #ff6f5c;
}
</style>
</head>
<body>
<form id="form1" >
<div class="container">
<p><img src="/content/public/images/error_${status}.png"/></p>
<p class="font">${error},<a onclick="errorDetail(true)" href="javascript: void(0)" rel="external nofollow" >點擊查看明細</a>!</p>
<p><button type="button" class="btn btn-back" id="btnBack" >返回</button></p>
</div>
<div id="container-info">
<span class="btn btn-close" onclick="errorDetail(false)">×</span>
<div class="panel panel-orange">
<div class="panel-heading">
錯誤說明
</div>
<div class="panel-body">
<#if path??>
<p><b>請求的URL:</b>${path}</p>
</#if>
<#if message??>
<p><b>異常信息:</b><span class="cor-r">${message}</span></p>
</#if>
<#if trace??>
<p><b>StackTrace:</b><br>${trace}</p>
</#if>
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function () {
var btn = document.getElementById("btnBack");
btn.onclick = function () {
var url = document.referrer;
if (url.indexOf("home/main") > 0) {
window.parent.tabDelete();
return;
}
window.history.back(-1);
}
}
function errorDetail(isShow) {
var con = document.getElementById("container-info");
con.className = isShow ? "show" : ""; // 兼容IE8
}
</script>
</form>
</body>
</html>
3)最后效果

錯誤頁面的展示優(yōu)先級
1、精確大于模糊
2、動態(tài)大于靜態(tài)
總結(jié)
到此這篇關(guān)于Spring Boot自定義錯誤視圖的方法詳解的文章就介紹到這了,更多相關(guān)springboot自定義錯誤視圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis-plus+達夢數(shù)據(jù)庫實現(xiàn)自動生成代碼的示例
這篇文章主要介紹了MyBatis-plus+達夢數(shù)據(jù)庫實現(xiàn)自動生成代碼的示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
在SpringBoot中使用UniHttp簡化天地圖路徑規(guī)劃調(diào)用實踐記錄(場景分析)
本文介紹了如何在SpringBoot項目中使用UniHttp簡化天地圖路徑規(guī)劃接口的調(diào)用,通過一個具體的例子展示了如何根據(jù)中文地址獲取經(jīng)緯度坐標(biāo),并使用UniHttp調(diào)用天地圖路徑規(guī)劃服務(wù),感興趣的朋友一起看看吧2025-02-02
SpringBoot整合Quartz實現(xiàn)動態(tài)配置的代碼示例
這篇文章將介紹如何把Quartz定時任務(wù)做成接口,實現(xiàn)以下功能的動態(tài)配置添加任務(wù),修改任務(wù),暫停任務(wù),恢復(fù)任務(wù),刪除任務(wù),任務(wù)列表,任務(wù)詳情,文章通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-07-07
jboss( WildFly)上運行 springboot程序的步驟詳解
這篇文章主要介紹了jboss( WildFly)上運行 springboot程序的步驟詳解,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02

