目录
一、RestControllerAdvice
@RestControllerAdvice、@ControllerAdvice 注解 可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute 并应用到所有@RequestMappingControllerAdvice需要增加 @ResponseBody
RestControllerAdvice不需要加 @ResponseBody
二、实例
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = BusinessException.class)
public ResponseEntity handlerBusinessException(BusinessException ex){
return new ResponseEntity(ex.getCodeEnum());
}
@ExceptionHandler(value = Exception.class)
public ResponseEntity handlerException(Exception ex){
LOGGER.error("发生全局异常", ex);
return ResponseEntity.ofSystemBusy();
}
}
三、spring处理
3.1 bean初始化流程
WebMvcConfigurationSupport.handlerExceptionResolver->
WebMvcAutoConfiguration.configureHandlerExceptionResolvers ->
WebMvcConfigurationSupport.addDefaultHandlerExceptionResolvers ->
ExceptionHandlerExceptionResolver.afterPropertiesSet ->
ExceptionHandlerExceptionResolver.initExceptionHandlerAdviceCache
ExceptionHandlerExceptionResolver这个类里存储了所有ControllerAdvice注解的处理器
初始化HandlerExceptionResolver
简言之,一共两件事
1、初始化HandlerExceptionResolverComposite,这个存储着HandlerExceptionResolver处理器列表
2、初始化ExceptionHandlerExceptionResolver的缓存,存储着所有ControllerAdvice主键的处理器
3.2 全局处理流程
进入doService方法,开始业务处理,当遇到异常时在processDispatchResult方法里进行处理,接着对于非ModelAndViewDefiningException的异常,在processHandlerException中处理,在这个方法中会调用HandlerExceptionResolverComposite(这个在前面我们已经知道,项目启动的时候已经初始化了所有的HandlerExceptionResolver,其中包含了ExceptionHandlerExceptionResolver,而ExceptionHandlerExceptionResolver又包含了自定义的ControllerAdvice主键类)的resolveException方法进行处理