public class ExceptionHandlerMethodResolver {
MethodFilter EXCEPTION_HANDLER_METHODS = method ->
AnnotatedElementUtils.hasAnnotation(method, ExceptionHandler.class);
Map<Class<? extends Throwable>, Method> mappedMethods = new HashMap<>(16);
public ExceptionHandlerMethodResolver(Class<?> handlerType) {
// 在 @ControllerAdvice 注解的类中获取 @ExceptionHandler 注解的方法
for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) {
// 获取 @ExceptionHandler 其属性value的值,即代表拦截需要处理的异常
for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) {
// 异常类型 & @ExceptionHandler 注解的方法
addExceptionMapping(exceptionType, method);
}
}
}
private void addExceptionMapping(Class<? extends Throwable> exceptionType, Method method) {
Method oldMethod = this.mappedMethods.put(exceptionType, method);
}
}