在项目中,经常会使用ExceptionHandler来作为全局性的异常处理中心。那么ExceptionHandler处理异常的原理是什么呢,今天就来分析一下。
ExceptionHandler使用示例
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = RuntimeException.class)
public String handle(){
return "error";
}
}
复制代码
使用还是很简单的,在类上面添加ControllerAdvice注解,在方法上面添加ExceptionHandler注解,就可以在方法里处理相应的异常信息了。
原理剖析
ControllerAdvice和ExceptionHandler注解的作用
异常处理的核心类是ExceptionHandlerExceptionResolver,进入该类。查看afterPropertiesSet方法。
public void afterPropertiesSet() {
// Do this first, it may add ResponseBodyAdvice beans
initExceptionHandlerAdviceCache();
...
}
private void initExceptionHandlerAdviceCache() {
if (getApplicationContext() == null) {
return;
}
//这行代码会找出所有标记了ControllerAdvice注解的类
List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
AnnotationAwareOrderComparator.sort(adviceBeans);
for (ControllerAdviceBean adviceBean : adviceBeans) {
Class<?> beanType = adviceBean.getBeanType();
if (beanType == null) {
throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean);
}
//遍历这些类,找出有ExceptionHandler注解标注的方法。
ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(beanType);