簡介 Spring Boot
的出現極大的簡化了開發流程,封裝了不少實用的工具;今天要說的是2.x
版本中的異常處理,在Spring Boot
中其實已經給咱們實現好了異常處理方法;對應的Controller
是BasicErrorController
,咱們能夠去實現它,改爲本身的邏輯以及返回值,並且支持同步和異步。java
經過解析源碼咱們知道,BasicErrorController
經過ErrorAttributes
能夠自定義返回屬性,因此咱們能夠自定義一個ErrorAttributes
類只要實現ErrorAttributes
便可;默認Spring Boot
已經幫咱們實現了一個DefaultErrorAttributes
;若是咱們想要改變其中屬性咱們只須要繼承DefaultErrorAttributes
便可,好比下面 react
不過這裏有個小細節咱們必需要注意getErrorAttributes
第一個參數是WebRequest
,爲何要說這個呢? 由於Spring Boot 2.x
還有一套DefaultErrorAttributes
,名字長得如出一轍,傻傻分不清;若是你發現自定義的ErrorAttributes
沒法起做用,可能就是包沒引對。咱們一塊兒來看看web
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
自動註冊了MVC
的spring
org.springframework.boot.web.servlet.error.DefaultErrorAttributes
以下
編程
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration
也註冊了一套webflux
的異步
org.springframework.boot.web.reactive.error.DefaultErrorAttributes
怎麼樣看清楚了嗎,名字如出一轍,包名不同,功能也如出一轍, 這裏有個新概念webflux
,不懂的同窗自動跳轉 實戰Spring Boot 2.0 Reactive編程系列 - WebFlux初體驗 默認狀況Spring Boot
走的的是MVC
的,因此若是你繼承的是webflux
的DefaultErrorAttributes
那就確定不會起做用了,並且還有可能出現以下錯誤ide
*************************** APPLICATION FAILED TO START *************************** Description: The bean 'errorAttributes', defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/micro/cfg/CfgErrorAttributes.class] and overriding is disabled. Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true