Spring boot定製錯誤資料攜帶出去

2021-08-27 21:21:33 字數 1562 閱讀 2130

spring boot出現錯誤以後,會來到/error請求

會被basicerrorcontroller處理,自適應返回

瀏覽器訪問,返回頁面

客戶端訪問,返回json

獲取返回的響應資料

在abstracterrorcontroller中定義

basicerrorcontroller的父類

處理error請求,預設配置

@conditionalo****singbean

建立條件

當容器中,沒有errorcontroller元件的時候

才會,建立預設的錯誤處理元件basicerrorcontroller

1、完全來編寫乙個errorcontroller的實現類

或者編寫abstracterrorcontroller的子類,放在容器中

2、頁面上能用的資料,或者是json返回能用的資料

都是通過errorattributes.geterrorattributes得到

呼叫errorattributes.geterrorattributes

建立條件

當容器中,沒有errorattributes元件的時候

才會,建立乙個預設的defaulterrorattributes

預設進行資料處理

自定義errorattributes

為了簡單,繼承defaulterrorattributes

注入到容器中,重寫geterrorattributes方法

獲取父類的map,然後,在map中追加

自定義的錯誤資訊

//給容器中加入我們自己定義的errorattributes

@component

public

class

myerrorattributes

extends

defaulterrorattributes

}

異常處理器

輸出自定義異常的錯誤資訊

可以將map,放在request請求域中

myerrorattributes

在request請求域中,獲取ext屬性

ext,表示在異常處理器中,攜帶的資料

然後,追加到map中

最終效果

響應是自適應的

可以通過定製errorattributes,改變需要返回的內容

SpringBoot定製錯誤頁面和錯誤資料

直接丟擲異常,那麼瀏覽器是便會訪問錯誤頁面 public string error model model lang en charset utf 8 titletitle head 55555555555 5xx.html body html timestamp 時間戳 status 狀態碼 er...

SpringBoot定製錯誤的Json資料

1 自定義異常處理 返回定製json資料 1 controlleradvice 2public class myexceptionhandler 11 缺點 沒有自適應效果,只是會返回自定義的json資料 2 1 controlleradvice 2public class myexceptionh...

SpringBoot定製錯誤頁面

1 有模板引擎的情況下,例如404錯誤,將會在thymeleaf的templates的error下尋找404.html,如果找不到再尋找4xx.html 所有4開頭的錯誤狀態碼如果找不到特定的html頁面將會指向4xx.html 頁面可以獲取到的資訊 timestamp 時間戳 status 狀態碼...