spring全局异常拦截器如何实现

猿友 2021-06-22 14:07:13 浏览数 (2622)
反馈

本篇文章介绍了spring全局异常拦截器如何实现,本文可以实现在spring中手动构建全局异常拦截器。

你可能会问,Spring已经自带了全局异常拦截,为什么还要重复造轮子呢?

这是个好问题,我觉得有以下几个原因

  1. 装逼
  2. Spring的全局异常拦截只是针对于Spring MVC的接口,对于你的RPC接口就无能为力了
  3. 无法定制化
  4. 除了写业务代码,我们其实还能干点别的事

我觉得上述理由已经比较充分的解答了为什么要重复造轮子,接下来就来看一下怎么造轮子

造个什么样的轮子?

我觉得全局异常拦截应该有如下特性

  1. 使用方便,最好和spring原生的使用方式一致,降低学习成本
  2. 能够支持所有接口
  3. 调用异常处理器可预期,比如说定义了RuntimeException的处理器和Exception的处理器,如果这个时候抛出NullPointException,这时候要能没有歧义的选择预期的处理器

如何造轮子?

由于现在的应用基本上都是基于spring的,因此我也是基于SpringAop来实现全局异常拦截

首先先定义几个注解

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Component
  5. public @interface ExceptionAdvice {
  6. }
  7.  
  8. @Target(ElementType.METHOD)
  9. @Retention(RetentionPolicy.RUNTIME)
  10. @Documented
  11. public @interface ExceptionHandler {
  12. Class<? extends Throwable>[] value();
  13. }
  14.  
  15. @Target(ElementType.METHOD)
  16. @Retention(RetentionPolicy.RUNTIME)
  17. @Documented
  18. public @interface ExceptionIntercept {
  19. }

@ExceptionAdvice 的作用是标志定义异常处理器的类,方便找到异常处理器

@ExceptionHandler 的作用是标记某个方法是处理异常的,里面的值是能够处理的异常类型

@ExceptionIntercept 的作用是标记需要异常拦截的方法

接下来定义统一返回格式,以便出现错误的时候统一返回

  1. @Data
  2. public class BaseResponse<T> {
  3. private Integer code;
  4. private String message;
  5. private T data;
  6.  
  7. public BaseResponse(Integer code, String message) {
  8. this.code = code;
  9. this.message = message;
  10. }
  11. }

然后定义一个收集异常处理器的类

  1. public class ExceptionMethodPool {
  2. private List<ExceptionMethod> methods;
  3. private Object excutor;
  4.  
  5. public ExceptionMethodPool(Object excutor) {
  6. this.methods = new ArrayList<ExceptionMethod>();
  7. this.excutor = excutor;
  8. }
  9.  
  10. public Object getExcutor() {
  11. return excutor;
  12. }
  13.  
  14. public void add(Class<? extends Throwable> clazz, Method method) {
  15. methods.add(new ExceptionMethod(clazz, method));
  16. }
  17.  
  18. //按序查找能够处理该异常的处理器
  19. public Method obtainMethod(Throwable throwable) {
  20. return methods
  21. .stream()
  22. .filter(e -> e.getClazz().isAssignableFrom(throwable.getClass()))
  23. .findFirst()
  24. .orElseThrow(() ->new RuntimeException("没有找到对应的异常处理器"))
  25. .getMethod();
  26. }
  27.  
  28. @AllArgsConstructor
  29. @Getter
  30. class ExceptionMethod {
  31. private Class<? extends Throwable> clazz;
  32. private Method method;
  33. }
  34. }

ExceptionMethod 里面有两个属性

  • clazz:这个代表着能够处理的异常
  • method:代表着处理异常调用的方法

ExceptionMethodPool 里面按序存放所有异常处理器,excutor是执行这些异常处理器的对象

接下来把所有定义的异常处理器收集起来

  1. @Component
  2. public class ExceptionBeanPostProcessor implements BeanPostProcessor {
  3. private ExceptionMethodPool exceptionMethodPool;
  4. @Autowired
  5. private ConfigurableApplicationContext context;
  6.  
  7. @Override
  8. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  9. Class<?> clazz = bean.getClass();
  10. ExceptionAdvice advice = clazz.getAnnotation(ExceptionAdvice.class);
  11. if (advice == null) return bean;
  12. if (exceptionMethodPool != null) throw new RuntimeException("不允许有两个异常定义类");
  13. exceptionMethodPool = new ExceptionMethodPool(bean);
  14.  
  15. //保持处理异常方法顺序
  16. Arrays.stream(clazz.getDeclaredMethods())
  17. .filter(method -> method.getAnnotation(ExceptionHandler.class) != null)
  18. .forEach(method -> {
  19. ExceptionHandler exceptionHandler = method.getAnnotation(ExceptionHandler.class);
  20. Arrays.stream(exceptionHandler.value()).forEach(c -> exceptionMethodPool.add(c,method));
  21. });
  22. //注册进spring容器
  23. context.getBeanFactory().registerSingleton("exceptionMethodPool",exceptionMethodPool);
  24. return bean;
  25. }
  26. }

ExceptionBeanPostProcessor 通过实现BeanPostProcessor 接口,在bean初始化之前,把所有异常处理器塞进 ExceptionMethodPool,并把其注册进Spring容器

然后定义异常处理器

  1. @Component
  2. public class ExceptionProcessor {
  3. @Autowired
  4. private ExceptionMethodPool exceptionMethodPool;
  5.  
  6. public BaseResponse process(Throwable e) {
  7. return (BaseResponse) FunctionUtil.computeOrGetDefault(() ->{
  8. Method method = exceptionMethodPool.obtainMethod(e);
  9. method.setAccessible(true);
  10. return method.invoke(exceptionMethodPool.getExcutor(),e);
  11. },new BaseResponse(0,"未知错误"));
  12. }
  13. }

这里应用了我自己通过函数式编程封装的一些语法糖,有兴趣的可以看下

最后通过AOP进行拦截

  1. @Aspect
  2. @Component
  3. public class ExceptionInterceptAop {
  4. @Autowired
  5. private ExceptionProcessor exceptionProcessor;
  6.  
  7. @Pointcut("@annotation(com.example.exception.intercept.ExceptionIntercept)")
  8. public void pointcut() {
  9. }
  10.  
  11. @Around("pointcut()")
  12. public Object around(ProceedingJoinPoint point) {
  13. return computeAndDealException(() -> point.proceed(),
  14. e -> exceptionProcessor.process(e));
  15. }
  16.  
  17. public static <R> R computeAndDealException(ThrowExceptionSupplier<R> supplier, Function<Throwable, R> dealFunc) {
  18. try {
  19. return supplier.get();
  20. } catch (Throwable e) {
  21. return dealFunc.apply(e);
  22. }
  23. }
  24. @FunctionalInterface
  25. public interface ThrowExceptionSupplier<T> {
  26. T get() throws Throwable;
  27. }
  28. }

到这里代码部分就已经完成了,我们来看下如何使用

  1. @ExceptionAdvice
  2. public class ExceptionConfig {
  3. @ExceptionHandler(value = NullPointerException.class)
  4. public BaseResponse process(NullPointerException e){
  5. return new BaseResponse(0,"NPE");
  6. }
  7.  
  8. @ExceptionHandler(value = Exception.class)
  9. public BaseResponse process(Exception e){
  10. return new BaseResponse(0,"Ex");
  11. }
  12.  
  13. }
  14.  
  15. @RestController
  16. public class TestControler {
  17.  
  18. @RequestMapping("/test")
  19. @ExceptionIntercept
  20. public BaseResponse test(@RequestParam("a") Integer a){
  21. if (a == 1){
  22. return new BaseResponse(1,a+"");
  23. }
  24. else if (a == 2){
  25. throw new NullPointerException();
  26. }
  27. else throw new RuntimeException();
  28. }
  29. }

我们通过@ExceptionAdvice标志定义异常处理器的类,然后通过@ExceptionHandler标注处理异常的方法,方便收集

最后在需要异常拦截的方法上面通过@ExceptionIntercept进行异常拦截

我没有使用Spring那种匹配最近父类的方式寻找匹配的异常处理器,我觉得这种设计是一个败笔,理由如下

  • 代码复杂
  • 不能一眼看出要去调用哪个异常处理器,尤其是定义的异常处理器非常多的时候,要是弄多个定义类就更不好找了,可能要把所有的处理器看完才知道应该调用哪个

出于以上考虑,我只保留了一个异常处理器定义类,并且匹配顺序和方法定义顺序一致,从上到下依次匹配,这样只要找到一个能够处理的处理器,那么就知道了会如何调用


0 人点赞