spring boot自定義異常信息

/error端點的實現來源於springboot的org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController它的具體定義如下:
在這裏插入圖片描述
從源碼中可以看到,它的實現非常簡單,通過調用getErrorAttribute方法來根據請求參數組織錯誤信息的返回結果,而這裏的getErrorAttributes方法會將具體信息組織邏輯委託給org.springframework.boot.web.servlet.error.ErrorAttributes接口提供的getErrorAttributes來實現。在spring boot的自動化配置中,默認會採用org.springframework.boot.web.servlet.error.DefaultErrorAttributes作爲該接口的實現(ErrorMvcAutoConfiguration)。
如下代買定義了error處理的自動化配置
在這裏插入圖片描述
該接口的默認實現採用了*@ConditionalOnMissingBean*修飾,說明DefaultErrorAttributes對象實例僅在沒有ErrorAttributes接口的實例時纔會被創建來使用,所以我只需要自己編寫自定義的ErrorAttributes接口實現類,就能替代默認實現。簡單的實例除去exception信息

public class DidErrorAttributes extends DefaultErrorAttributes{

	@Override
	public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
		Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
		map.remove("exception");
		return map;
	}

}

在這裏插入圖片描述
這樣就可以替代了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章