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(完整類路徑)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM