Dubbo自定义Filter统一处理异常

Dubbo版本:2.7apache

 

 

使用自定义Filter注意事项app

 

一、自定义名称不能和默认Filter相同,不然可能不生效spa

 

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

 

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

 

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

 

自定义Filterrpc

@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.Filterget

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

相关文章
相关标签/搜索