dubbo一次异常引发的ExceptionFilter处理分析

最近在使用dubbo的项目中,线上环境因业务异常(比如输入框校验异常),导致Dubbo提示报异常,异常如下所示。

[DUBBO] Got unchecked and undeclared exception which called by 10.0.0.xx. service: com.xxx.common.business.dwh.DubboxxxBusiness, method:xxx, exception: com.xxx.common.exception.xxxException: 非法参数:类型不匹配...

由于在系统中规定记录业务异常的级别为warn级别,所以配置了RestControllerAdvice对异常做统一处理,这条error日志不太符合当前的要求,然后就开始本次调查之旅。

1、问题推断

首先说一下,项目的背景:有两个服务,web服务A和功能模块服务B。A中接收前端的请求,并转发给B服务处理。A调用B就是使用的dubbo的方式。在A中定义了RestControllerAdvice统一异常处理类,以warn级别处理接收业务异常。
这个异常的字面起因是由于识别不到异常导致的,首先根据日志里的业务异常,定位到具体接口和实现类。然后,根据信息创建一个异常数据,比如提示的是“类型不匹配”,我们就输入一个错误的类型,debug回溯异常产生的过程。
最终我们通过报错日志信息,定位到了org.apache.dubbo.rpc.filter.ExceptionFilter。

2、阅读源码,分析逻辑

dubbo版本:2.7.8
最主要的源码大约有100多行,其中最核心的处理逻辑主要在onResponse方法中实现。

@Activate(group = CommonConstants.PROVIDER)
public class ExceptionFilter implements Filter, Filter.Listener {
    private Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);

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

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
            try {
                Throwable exception = appResponse.getException();

                // directly throw if it's checked exception
                if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                    return;
                }
                // directly throw if the exception appears in the signature
                try {
                    Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                    Class<?>[] exceptionClassses = method.getExceptionTypes();
                    for (Class<?> exceptionClass : exceptionClassses) {
                        if (exception.getClass().equals(exceptionClass)) {
                            return;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return;
                }

                // for the exception not found in method's signature, print ERROR message in server's log.
                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);

                // directly throw if exception class and interface class are in the same jar file.
                String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                    return;
                }
                // directly throw if it's JDK exception
                String className = exception.getClass().getName();
                if (className.startsWith("java.") || className.startsWith("javax.")) {
                    return;
                }
                // directly throw if it's dubbo exception
                if (exception instanceof RpcException) {
                    return;
                }

                // otherwise, wrap with RuntimeException and throw back to the client
                appResponse.setException(new RuntimeException(StringUtils.toString(exception)));
            } catch (Throwable e) {
                logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
            }
        }
    }

    @Override
    public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
        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);
    }

    // For test purpose
    public void setLogger(Logger logger) {
        this.logger = logger;
    }
}

从源码中,可以读出来,这个处理类是在provider端处理抛出的异常数据。
下面主要分析onResponse方法中的处理流程。整体上,代码只要满足其中一个逻辑就会放回,不在继续执行后续步骤。

逻辑0
 if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
 ....
 }

调用结果有异常且未实现GenericService接口,进入后续判断逻辑,否则直接返回。
'GenericService’主要是指泛化接口,实现方式主要用于服务器端没有 API 接口及模型类元的情况,参数及返回值中的所有 POJO 均用 Map 表示,通常用于框架集成,比如:实现一个通用的远程服务 Mock 框架,可通过实现 GenericService 接口处理所有服务请求。
官网
不是本次讨论的重点。

逻辑1
// directly throw if it's checked exception
                if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                    return;
                }

不是RuntimeException类型的异常,并且是受检异常(继承Exception),直接抛出。

逻辑2
// directly throw if the exception appears in the signature
                try {
                    Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                    Class<?>[] exceptionClassses = method.getExceptionTypes();
                    for (Class<?> exceptionClass : exceptionClassses) {
                        if (exception.getClass().equals(exceptionClass)) {
                            return;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return;
                }

如果在provider端的api明确写明抛出运行时异常,则会直接被抛出。
下一步,就是这次抛出异常的出处。

// for the exception not found in method's signature, print ERROR message in server's log.
                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);

到这里就知道为啥,会报这个error级别的异常了,就是consumer端无法识别provider抛出的业务异常。所以显而易见的处理方法有几个:

1、provider实现GenericService接口;
2、provider的api明确写明throws XxxException,发布provider(其中XxxException是自定义的业务异常);

我们继续看完其他逻辑,会有更多的处理方法。

逻辑3
// directly throw if exception class and interface class are in the same jar file.
                String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                    return;
                }

如果异常类和接口类在同一个jar包中,直接抛出。

逻辑4
// directly throw if it's JDK exception
                String className = exception.getClass().getName();
                if (className.startsWith("java.") || className.startsWith("javax.")) {
                    return;
                }

以java.或javax.开头的异常直接抛出。

逻辑5
// directly throw if it's dubbo exception
                if (exception instanceof RpcException) {
                    return;
                }

dubbo自身的异常,直接抛出。

逻辑6
// otherwise, wrap with RuntimeException and throw back to the client
                appResponse.setException(new RuntimeException(StringUtils.toString(exception)));

不满足上述条件,会做toString处理并被封装成RuntimeException抛出。

看完整个逻辑,如何正确的捕获业务异常的方式又多了几种:

1、使用受检异常(继承Exception),一般情况下不太合适。
2、不用异常,使用错误码。这个是可以实现的,使用一个异常信息类,封装异常信息,并要求在定义dubbo接口时,均采用这个异常信息类。
public class JsonResponse<T> implements Serializable{
    private T result;
    private String errorCode;
    private String message;
}
3、把异常放到provider-api的jar包中。
4、实现dubbo的filter,自定义provider的异常处理逻辑。这种方式参考

主要参考文档:
浅谈 Dubbo 的 ExceptionFilter 异常处理
dubbo filter 扩展 以及 重写 dubbo ExceptionFilter
springboot dubbo服务端抛出自定义异常,消费端捕获却是RuntimeException异常
实现泛化调用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值