• SpringCloud-技术专区-Gateway优雅的处理Filter抛出的异常


     

     

           Filter的位置相对比较尴尬,在MVC层之外,所以无法使用SpringMVC统一异常处理。

           虽然SpringCouldGateway支持MVC注解,可以使用SpringMVC统一异常处理处理异常https://www.jianshu.com/p/6f631f3e00b9

    但是对于Filter抛出的异常依然束手无策 : - ( 


    解决方案:

    SpringCloudGateway异常处理类间关系
               在org.springframework.boot.autoconfigure.web.reactive.error包下有三个类用于处理异常。
    (这里强烈建议看一下源码,了解一下具体的处理思路)

     
    image.png


            很明显,上面两个是处理异常的一些逻辑,下面的那个类是异常的配置类,所以我们只需要继承DefaultErrorWebExceptionHandler然后将我们

    处理异常的逻辑替换原有的逻辑。然后通过配置类,将自己写的类替换原有的类即可。

    需要重写的方法

    @Slf4j
    public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler {
    
        public GlobalExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
            super(errorAttributes, resourceProperties, errorProperties, applicationContext);
        }
    
        @Override
        protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
            Throwable error = super.getError(request);
           // todo 添加自己处理异常的逻辑
            return null;
        }
    
        // 指定响应处理方法为JSON处理的方法
        @Override
        protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
            return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
        }
        //设置返回状态码,由于我的返回json里面已经包含状态码了,不用这里的状态码,所以这里直接设置200即可
        @Override
        protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
            return HttpStatus.valueOf(200);
        }
    }

    配置类替换成自己的处理异常类

    @Configuration
    @EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
    public class ErrorHandlerConfiguration {
    
        private final ServerProperties serverProperties;
    
        private final ApplicationContext applicationContext;
    
        private final ResourceProperties resourceProperties;
    
        private final List<ViewResolver> viewResolvers;
    
        private final ServerCodecConfigurer serverCodecConfigurer;
    
        public ErrorHandlerConfiguration(ServerProperties serverProperties,
                                         ResourceProperties resourceProperties,
                                         ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                         ServerCodecConfigurer serverCodecConfigurer,
                                         ApplicationContext applicationContext) {
            this.serverProperties = serverProperties;
            this.applicationContext = applicationContext;
            this.resourceProperties = resourceProperties;
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
            GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler(
                    errorAttributes,
                    this.resourceProperties,
                    this.serverProperties.getError(),
                    this.applicationContext);
            exceptionHandler.setViewResolvers(this.viewResolvers);
            exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
            exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
            return exceptionHandler;
        }
    }

        这样我们就将统一异常处理指向了我们自己写的处理类了,剩下的就是具体的处理逻辑。

         因为我们想延用SpringMVC处理异常的注解,所以我们需要解析SpringMVC的注解,然后做一些相应的逻辑处理即可。具体的思路是这样的。

    1. 获取Spring容器中所有的类上标注@RestControllerAdvice注解的所有实例
    2. 获取实例里面所有标注@ExceptionHandler的方法。
    3. 创建一个map,key是注解中的value(处理异常的类型),value是方法。这样我们就将我们可以处理的异常和处理异常的方法关联起来了。
    4. 解决异常时,先获取异常的class和他所有的父类class。依次遍历map,直到找到第一个对应的处理方法,然后通过反射调用该方法。
    @Slf4j
    @Configuration
    public class ExceptionHandlerCore implements ApplicationRunner {
    
        /**
         * key是处理异常的类型
         * value是处理异常的方法
         */
        private HashMap<Class<? extends Throwable>, Node> exceptionHandlerMap;
    
        /**
         * 解析类上的注解
         * 将处理异常的方法注册到map中
         */
        private void register(Object exceptionAdvice) {
            Method[] methods = exceptionAdvice.getClass().getMethods();
            Arrays.stream(methods).forEach(method -> {
                ExceptionHandler exceptionHandler = method.getAnnotation(ExceptionHandler.class);
                if (Objects.isNull(exceptionHandler)) {
                    return;
                }
                Arrays.asList(exceptionHandler.value()).forEach(a -> exceptionHandlerMap.put(a, new Node(method, exceptionAdvice)));
            });
        }
    
        /**
         * 根据异常对象获取解决异常的方法
         *
         * @param throwable 异常对象
         * @return handler method
         */
        private Node getHandlerExceptionMethodNode(Throwable throwable) {
            ArrayList<Class<?>> superClass = this.getSuperClass(throwable.getClass());
            for (Class<?> aClass : superClass) {
                Node handlerNode = null;
                if ((handlerNode = exceptionHandlerMap.get(aClass)) != null) {
                    return handlerNode;
                }
            }
            return null;
        }
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            exceptionHandlerMap = new HashMap<>();
            log.info("-------------异常处理容器内存分配完毕-------------");
            Map<String, Object> beans = SpringContextHolder.getBeansWithAnnotation(RestControllerAdvice.class);
            log.info("-------------异常处理对象获取完毕-------------");
            beans.keySet()
                    .stream()
                    .map(beans::get)
                    .forEach(this::register);
            log.info("-------------异常处理方法注册完毕-------------");
        }
    
        /**
         * 对外暴露的处理异常的方法
         *
         * @param throwable 处理的异常
         * @return 调用异常后的返回值
         */
        public Object handlerException(Throwable throwable) {
            Node exceptionMethodNode = this.getHandlerExceptionMethodNode(throwable);
            if (Objects.isNull(exceptionMethodNode)) {
                throw new RuntimeException("没有处理异常的方法");
            }
          
            Object returnResult = null;
            try {
                returnResult = exceptionMethodNode.method.invoke(exceptionMethodNode.thisObj, throwable);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            return returnResult;
        }
    
        /**
         * 用于存放方法和方法所在的实例
         */
        private static class Node {
            Node(Method method, Object thisObj) {
                this.method = method;
                this.thisObj = thisObj;
            }
    
            Method method;
            Object thisObj;
        }
    
    
        /**
         * 获取该类的class以及所有父的class
         *
         * @param clazz this.class
         * @return list
         */
        public ArrayList<Class<?>> getSuperClass(Class<?> clazz) {
            ArrayList<Class<?>> classes = new ArrayList<>();
            classes.add(clazz);
            Class<?> suCl = clazz.getSuperclass();
            while (suCl != null) {
                classes.add(suCl);
                suCl = suCl.getSuperclass();
            }
            return classes;
        }
    }
    

      

    将该类,注入到刚才的我们自定义的异常处理类然后调用该类的handlerException方法即可。

    @Slf4j
    public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler {
    
        @Resource
        private ExceptionHandlerCore handlerCore;
        // ....
        /**
         * 统一处理异常信息
         */
        @Override
        @SuppressWarnings(value = "unchecked")
        protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
            Throwable error = super.getError(request);
            //调用处理异常的方法,并将对象转换成map
            Object o = handlerCore.handlerException(error);
            String json = JsonHelper.objectToJson(o);
            return JsonHelper.jsonToObject(json, HashMap.class);
        }
       // ...
    

      

    涉及到的工具类如下:

    JsonHelper

    public class JsonHelper {
    
        /**
         * Json美化输出工具
         * @param json json string
         * @return beauty json string
         */
        public static String toPrettyFormat(String json) {
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            return gson.toJson(jsonObject);
        }
    
        /**
         * Json转换成对象
         * @param json json string
         * @param <T> 对象类型
         * @return T
         */
        public static  <T> T jsonToObject(String json,Class<T> t){
            Gson gson = new Gson();
            return gson.fromJson(json,t);
        }
    
        /**
         * 对象转换成Json字符串
         * @param object obj
         * @return json string
         */
        public static String objectToJson(Object object){
            Gson gson = new Gson();
            return gson.toJson(object);
        }
    
    }
    

      

    SpringContextHolder

    @Component
    public class SpringContextHolder implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringContextHolder.applicationContext = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext() {
            assertApplicationContext();
            return applicationContext;
        }
    
        public static <T> T getBean(Class<T> requiredType) {
            assertApplicationContext();
            return applicationContext.getBean(requiredType);
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String beanName) {
            assertApplicationContext();
            return (T) applicationContext.getBean(beanName);
        }
    
        /**
         * 通过类上的注解获取类
         *
         * @param annotation anno
         * @return map
         */
        public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
            assertApplicationContext();
            return applicationContext.getBeansWithAnnotation(annotation);
        }
    
        private static void assertApplicationContext() {
            if (SpringContextHolder.applicationContext == null) {
                throw new RuntimeException("application Context属性为null,请检查是否注入了SpringContextHolder!");
            }
        }
    
    }
    

      

    测试

    编写异常处理类

    @RestControllerAdvice
    public class GlobalExceptionHandlerAdvice {
    
        @ExceptionHandler(Throwable.class)
        public xxx handler(Throwable e){
            return xxx;
        }
    }
    

      

  • 相关阅读:
    bzoj 1015: [JSOI2008]星球大战starwar【并查集】
    bzoj 1026: [SCOI2009]windy数【数位dp】
    bzoj 3231: [Sdoi2008]递归数列【矩阵乘法】
    bzoj 4198: [Noi2015]荷马史诗【哈夫曼树+贪心】
    bzoj 1093: [ZJOI2007]最大半连通子图【tarjan+拓扑排序+dp】
    bzoj 3209: 花神的数论题【数位dp】
    bzoj [JSOI2010]Group 部落划分 Group【二分+并查集】
    bzoj 1087: [SCOI2005]互不侵犯King【状压dp】
    bzoj 2730: [HNOI2012]矿场搭建【tarjan】
    bzoj 1878: [SDOI2009]HH的项链【树状数组】
  • 原文地址:https://www.cnblogs.com/liboware/p/13225874.html
Copyright © 2020-2023  润新知