Dubbo的异常处理

最近在整Dubbo的框架,使用zookeeper做注册中心,项目中有service层作为provider(提供者),web层作为consumer(消费者),当在做自定义异常的抛出时,遇到了问题:

1、web层不能识别异常为自定义异常类型,异常类型为RuntimeException。

2、当修改识别类型为RuntimeException时,从异常当中获取到的message,多出了一大堆异常堆栈的信息。

就这两个问题,在网上搜索了很多资料,大部分都把Dubbo中的ExceptionFilter代码贴出来,然后分析逻辑,这里也将代码贴一下(以下是改过之后的代码,因为最终我选用了改源码的形式解决问题。)。

/*
 * Copyright 1999-2011 Alibaba Group.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.rpc.filter;

import java.lang.reflect.Method;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.service.GenericService;

/**
 * ExceptionInvokerFilter
 * <p>
 * 功能:
 * <ol>
 * <li>不期望的异常打ERROR日志(Provider端)<br>
 * 不期望的日志即是,没有的接口上声明的Unchecked异常。
 * <li>异常不在API包中,则Wrap一层RuntimeException。<br>
 * RPC对于第一层异常会直接序列化传输(Cause异常会String化),避免异常在Client出不能反序列化问题。
 * </ol>
 *
 * @author william.liangf
 * @author ding.lid
 */
@Activate(group = Constants.PROVIDER)
public class ExceptionFilter implements Filter {

    private final Logger logger;

    public ExceptionFilter() {
        this(LoggerFactory.getLogger(ExceptionFilter.class));
    }

    public ExceptionFilter(Logger logger) {
        this.logger = logger;
    }

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            Result result = invoker.invoke(invocation);
            if (result.hasException() && GenericService.class != invoker.getInterface()) {
                try {
                    Throwable exception = result.getException();

                    // 如果是checked异常,直接抛出
                    if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                        return result;
                    }
                    // 在方法签名上有声明,直接抛出
                    try {
                        Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                        Class<?>[] exceptionClassses = method.getExceptionTypes();
                        for (Class<?> exceptionClass : exceptionClassses) {
                            if (exception.getClass().equals(exceptionClass)) {
                                return result;
                            }
                        }
                    } catch (NoSuchMethodException e) {
                        return result;
                    }

                    // 未在方法签名上定义的异常,在服务器端打印ERROR日志
                    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);

                    // 异常类和接口类在同一jar包里,直接抛出
                    String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                    String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                    if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                        return result;
                    }
                    // 是JDK自带的异常,直接抛出
                    String className = exception.getClass().getName();
                    if (className.startsWith("java.") || className.startsWith("javax.")) {
                        return result;
                    }
                    if (className.startsWith("******") ||  className.startsWith("******")) {
                        logger.debug("===========自定义异常,直接抛出===========");
                        return result;
                    }
                    
                    // 是Dubbo本身的异常,直接抛出
                    if (exception instanceof RpcException) {
                        return result;
                    }
                    
                    // 否则,包装成RuntimeException抛给客户端
                    return new RpcResult(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);
                    return result;
                }
            }
            return result;
        } catch (RuntimeException e) {
            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);
            throw e;
        }
    }

}

其中的

if (className.startsWith("******") ||  className.startsWith("******")) {
    logger.debug("===========自定义异常,直接抛出===========");
    return result;
}

这一部分是我自己新添的代码,其中的**********是我们项目内部的自定义异常的包名,为项目保密在这里以******代替。

关于这里面的逻辑,在这里我就不过多赘述,注释都写的很清楚了。

而出现我所说的1和2两个情况,是在这段代码中,并没有检测自定义异常,甚至RuntimeException。

而是直接将不符合条件的异常全部进行了RuntimeException的包装。

                    // 否则,包装成RuntimeException抛给客户端
                    return new RpcResult(new RuntimeException(StringUtils.toString(exception)));

注意这里的StringUtils.toString。就是这个操作,将本来就几个字的message,直接给整成了一大堆带异常堆栈的信息。

这里要说明一下,为什么要贴出来ExceptionFilter的代码,因为provider抛出异常后,经过dubbo,然后在consumer捕获异常时,进行了异常的反序列化,ExceptionFilter负责的就是将异常还原包装。

所以,看到这里,问题就很明确了:

1、ExceptionFilter并不认识我自定义的异常。

2、ExceptionFilter没有检测RuntimeException异常(我的自定义异常继承了RuntimeException)。

依照ExceptionFilter的逻辑,解决办法有以下几种:

1、 将该异常的包名以"java.或者"javax. " 开头,但自己的项目都有自己特定的包名,所以弃用。

2、使用受检异常(继承Exception),继承根Exception,鬼知道会出现其他什么BUG,pass。

3、 把自定义异常放到provider的api模块中,每个api都定义自定义异常的话,平白增加了很多工作量,pass。

4、 provider实现GenericService接口,查了很多资料,也看到有人使用了这种方法,要弃用$invoke方法,最终也没有成功,懒惰的我也就没去试,有兴趣的朋友可以试试,然后跟我说说是个什么情况(我得懒到什么程度)。

5、provider的api明确写明抛出的异常,我连自定义异常放到api里面都懒得做,你让我每个接口都写抛出异常?开个玩笑。弃用这种方法的原因有三:1)在做这个异常处理的时候,已经完成了一部分代码了,要加抛出异常,是个不小的工作量。2)抛出的自定义异常只为了中止代码执行,返回给前台做消息提示,所以不涉及到业务的处理。3)添加抛出异常,增加了开发的工作量,也会影响到开发时专注于业务处理的初衷。

6、让ExceptionFilter支持自定义异常,修改源码使之直接抛出自定义异常。这种解决办法无疑是工作量最小,影响最小的了。但这其中也有一个隐患,如果要进行dubbo的版本更新的话,就必须将新的版本的ExceptionFilter也去修改。在此希望Dubbo能够支持配置自定义的ExceptionFilter。

转载于:https://my.oschina.net/hellerzhang/blog/1826617

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值