zoukankan      html  css  js  c++  java
  • Dubbo自定义Filter统一处理异常

    Dubbo版本:2.7

    使用自定义Filter注意事项

    1、自定义名称不能和默认Filter相同,否则可能不生效

    2、只用定义Filter类和META-INF下的文本文件,不用添加配置,@Activate注解会自动激活

    3、业务最好抛RpcException异常,抛其它RuntimeException子类,方法中的exception会识别为RuntimeException,而不是异常子类

    4、ResultCustom为自定义返回对象,Filter捕获异常后转换为该对象返回给客户端

    自定义Filter

    @Activate(group = CommonConstants.PROVIDER)
    public class NewFilter extends ListenableFilter {
    
        public NewFilter() {
            super.listener = new NewFilter.ExceptionListener();
        }
    
        public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
            return invoker.invoke(invocation);
        }
    
        static class ExceptionListener implements Listener {
    
            public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation)         {
    
                if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
    
                    try {
    
                        Throwable exception = appResponse.getException();
    
                        if (exception instanceof RpcException) {
      
                 ResultCustom response = ResultCustom.error(exception.getMessage());
                         appResponse.setValue(response);
                         appResponse.setException(null);
    
                         return;
                        }
    
                    } catch (Throwable e) {
                        return;
                    }
                }
            }
        }
    }

    文本文件resources-->META-INF-->dubbo-->org.apache.dubbo.rpc.Filter

    newFilter=xx.NewFilter(完整类路径)

  • 相关阅读:
    洛谷P1330 封锁阳光大学
    洛谷P1341 无序字母对
    Bzoj1059 [ZJOI2007]矩阵游戏
    POJ2337 Catenyms
    Bzoj2342 [Shoi2011]双倍回文
    Bzoj1009 [HNOI2008]GT考试
    Bzoj3670 [Noi2014]动物园
    POJ2406 Power Strings
    POJ 2752 Seek the Name, Seek the Fame
    POJ3522 Slim Span
  • 原文地址:https://www.cnblogs.com/gossip/p/11734654.html
Copyright © 2011-2022 走看看