简介 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