Dubbo Filter 过滤器 —— 自定义异常过滤器(ExceptionFilter)

背景介绍

许多项目中大家都会有一些自定义异常然后利用 ExceptionHandler 去做统一处理。
在我们的项目中同样用到,详见:SpringMVC之全局异常处理 ——统一返回格式
这种操作方式在常规项目使用中是没有任何问题的,但是当调用Dubbo接口时,服务方(provider) 抛出自定义异常,消费者拿到的却是一个 RuntimeException 并非我们自定义的异常类型。
并且还会打印Error级别的日志:

Got unchecked and undeclared exception which called by xxx.xxx.xxx.x. service: com.xxxx.xxx.service.xxxService, method: addxxx, exception: com.xxx.xxx.exception.xxxException: xxxxxxxxxxxx!, dubbo version: 2.7.4, current host: x.x.x.x

这对我们的日志监控报警系统非常不友好。
鉴于以上情况我们需要 重写 Dubbo的ExceptionFilter类,已达到我们想要的目的
关于Dubbo Filter扫盲知识详见我的另一篇博客:Dubbo Filter 过滤器(拦截器)的使用——dubbo.rpc.Filter

重写ExceptionFilter

根据不同的版本 ExceptionFilter 具体代码也有所区别大家去找到对应的类拷贝出来修改即可。博主目前使用的版本是: org.apache.dubbo 2.7.4

package com.xxx.trace.rpc.filter;

import java.lang.reflect.Method;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ListenableFilter;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * Dubbo 异常过滤器重写
 */
@Activate(
        group = {"provider"}
)
public class DubboExceptionFilter extends ListenableFilter {
    public DubboExceptionFilter() {
        super.listener = new DubboExceptionFilter.ExceptionListener();
    }

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }

    static class ExceptionListener implements Listener {
        private Logger logger = LoggerFactory.getLogger(DubboExceptionFilter.class);

        ExceptionListener() {
        }

        public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
            if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
                try {
                    Throwable exception = appResponse.getException();
                    if (exception instanceof RuntimeException || !(exception instanceof Exception)) {
                        try {
                            Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                            Class<?>[] exceptionClassses = method.getExceptionTypes();
                            Class[] var7 = exceptionClassses;
                            int var8 = exceptionClassses.length;

                            for(int var9 = 0; var9 < var8; ++var9) {
                                Class<?> exceptionClass = var7[var9];
                                if (exception.getClass().equals(exceptionClass)) {
                                    return;
                                }
                            }
                        } catch (NoSuchMethodException var11) {
                            return;
                        }
                        String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                        String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
						// 新增代码块 Begin
                        if (exceptionFile != null && exception.getClass().getName().startsWith("com.xxx")) {
                            //判断异常类如果是com.xxx开头则属于自定义业务异常,无需额外处理,直接return 消费者拿到的就是 服务提供者锁抛出的异常
                            this.logger.info("DubboExceptionFilter 业务校验异常:" + exception.getMessage());
                            return;
                        }
						// 新增代码块 end
						
                        this.logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception);

                        if (serviceFile != null && exceptionFile != null && !serviceFile.equals(exceptionFile)) {
                        // 因为这里有判断!serviceFile.equals(exceptionFile) 所以新增代码如果写在这里有一定的风险会导致此处无法进入该IF内部
                            String className = exception.getClass().getName();
                            if (!className.startsWith("java.") && !className.startsWith("javax.")) {
                                if (!(exception instanceof RpcException)) {
                                    appResponse.setException(new RuntimeException(StringUtils.toString(exception)));
                                }
                            }
                        }
                    }
                } catch (Throwable var12) {
                    this.logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + var12.getClass().getName() + ": " + var12.getMessage(), var12);
                }
            }
        }

        public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
            this.logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
        }

        public void setLogger(Logger logger) {
            this.logger = logger;
        }
    }
}

然后在resources目录下新建META-INF文件夹,然后建立子文件夹dubbo,最后新建文件com.alibaba.dubbo.rpc.Filter。(敲黑板划重点拉!这里不要弄错了)
在文件中新增:dubboExceptionFilter=com.xxx.trace.rpc.filter.DubboExceptionFilter
在这里插入图片描述

  • dubboExceptionFilter :就是你给这个过滤器取的名称
  • com.xxx.trace.rpc.filter.DubboExceptionFilter:过滤器对应的路径

过滤器配置

在大家各自的 dubbo-provider.xml 中新增该过滤器即可,多个过滤器可以以英文逗号 “ , ” 隔开。

<dubbo:provider filter="traceId,dubboExceptionFilter,-exception" version="${dubbo.provider.version:1.0}"/>

细心的朋友可能发现我在过滤器配置中还加了 -exception ,这是因为如果不加上 -exception 我们的过滤器确实生效了,但是Dubbo自身默认的 ExceptionFilter 任然在工作(一个异常抛出会依次进入两个过滤器),所以我们需要 禁用 掉默认的过滤器。 这一点是网上许多博客都没有说明的,请大家务必记住!!!
同理,如果我们想禁用其它的过滤器,都可以通过 -过滤器名称来实现。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
Dubbo服务过滤器可以用于在Dubbo服务调用的过程中对请求和响应进行预处理和后处理,例如权限控制、日志记录、统计信息等。在Dubbo中,可以通过配置<provider>或<consumer>标签下的<filter>元素来添加服务过滤器。具体的配置方法如下: 1. 创建一个服务过滤器类,实现org.apache.dubbo.common.extension.Activate接口,并重写filter方法。例如: ```java @Activate(group = "provider") public class MyFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { // 在这里添加过滤器的逻辑 return invoker.invoke(invocation); } } ``` 2. 在服务提供者或服务消费者的配置文件中,添加<filter>元素来引用服务过滤器。例如: ```xml <!-- 服务提供者配置 --> <dubbo:service interface="com.example.SomeService" ref="someService"> <dubbo:method name="someMethod" timeout="5000"> <dubbo:filter ref="myFilter" /> </dubbo:method> </dubbo:service> <!-- 服务消费者配置 --> <dubbo:reference id="someService" interface="com.example.SomeService"> <dubbo:method name="someMethod" timeout="5000"> <dubbo:filter ref="myFilter" /> </dubbo:method> </dubbo:reference> ``` 注意,<filter>元素必须放在<method>元素内部,以便对每个方法都应用过滤器。如果想要对所有方法都应用过滤器,则可以将<filter>元素放在<service>或<reference>元素内部。另外,如果服务过滤器需要传递参数,则可以通过<parameter>元素来配置。例如: ```xml <dubbo:filter ref="myFilter"> <dubbo:parameter key="param1" value="value1" /> <dubbo:parameter key="param2" value="value2" /> </dubbo:filter> ``` 在服务过滤器中可以通过调用invocation.getAttachment(key)方法来获取这些参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhibo_lv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值