javascript
Spring boot定制错误数据携带出去
定制錯誤數據
Spring boot出現錯誤以后,會來到/error請求
會被BasicErrorController處理,自適應返回
瀏覽器訪問,返回頁面
客戶端訪問,返回json
getErrorAttributes
獲取返回的響應數據
在AbstractErrorController中定義
BasicErrorController的父類
BasicErrorController
處理Error請求,默認配置
@ConditionalOnMissingBean
創建條件
當容器中,沒有ErrorController組件的時候
才會,創建默認的錯誤處理組件BasicErrorController
解決方法
1、完全來編寫一個ErrorController的實現類
或者編寫AbstractErrorController的子類,放在容器中
2、頁面上能用的數據,或者是json返回能用的數據
都是通過errorAttributes.getErrorAttributes得到
getErrorAttributes
調用errorAttributes.getErrorAttributes
errorAttributes
@ConditionalOnMissingBean
創建條件
當容器中,沒有ErrorAttributes組件的時候
才會,創建一個默認的DefaultErrorAttributes
DefaultErrorAttributes.getErrorAttributes
默認進行數據處理
自定義ErrorAttributes
為了簡單,繼承DefaultErrorAttributes
注入到容器中,重寫getErrorAttributes方法
獲取父類的Map,然后,在Map中追加
自定義的錯誤信息
//給容器中加入我們自己定義的ErrorAttributes @Component public class MyErrorAttributes extends DefaultErrorAttributes {//返回值的map就是頁面和json能獲取的所有字段@Overridepublic Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);map.put("company","atguigu");//我們的異常處理器攜帶的數據Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);map.put("ext",ext);return map;} }MyExceptionHandler
異常處理器
輸出自定義異常的錯誤信息
可以將map,放在request請求域中
MyErrorAttributes
在request請求域中,獲取ext屬性
Ext,表示在異常處理器中,攜帶的數據
然后,追加到map中
最終效果
響應是自適應的
可以通過定制ErrorAttributes,改變需要返回的內容
總結
以上是生活随笔為你收集整理的Spring boot定制错误数据携带出去的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring boot定制错误json数
- 下一篇: Spring boot配置嵌入式Serv