dubbo泛化调用使用GenericService自定义Exception变成GenericException的问题

使用GenericService调用dubbo接口的时候,发现抛出来的自定义异常都变成了GenericExecption。于是跟踪了源码看了一下,发现在GenericFilter中有一段


     Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));
        if ((result.hasException()) && 
          (!(result
          .getException() instanceof GenericException))) {
          return new RpcResult(new GenericException(result.getException()));
        }

这样就所有的非GenericException都转换成了GenericException
于是想到在服务提供方增加一个拦截器来实现自己想要的功能!具体实现如下:

import java.io.IOException;
import java.lang.reflect.Method;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream;
import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream;
import com.alibaba.dubbo.common.serialize.Serialization;
import com.alibaba.dubbo.common.utils.PojoUtils;
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.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.service.GenericException;
import com.alibaba.dubbo.rpc.support.ProtocolUtils;
/**
 * 这里order的源码是-20000,因为我们要执行在原逻辑之前
 * 因此我们这里改成了-25000
 **/
@Activate(group = Constants.PROVIDER, order = -25000)	
public class CustomGenericFilter implements Filter {

    @Override
    public Result invoke(Invoker invoker, Invocation inv) throws RpcException {
        if (inv.getMethodName().equals(Constants.$INVOKE) 
                && inv.getArguments() != null
                && inv.getArguments().length == 3
                && ! invoker.getUrl().getParameter(Constants.GENERIC_KEY, false)) {
            String name = ((String) inv.getArguments()[0]).trim();
            String[] types = (String[]) inv.getArguments()[1];
            Object[] args = (Object[]) inv.getArguments()[2];
            try {
                Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);
                Class[] params = method.getParameterTypes();
                if (args == null) {
                    args = new Object[params.length];
                }
                String generic = inv.getAttachment(Constants.GENERIC_KEY);
                if (StringUtils.isEmpty(generic)
                    || ProtocolUtils.isDefaultGenericSerialization(generic)) {
                    args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
                } else if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                    for(int i = 0; i < args.length; i++) {
                        if (byte[].class == args[i].getClass()) {
                            try {
                                UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[])args[i]);
                                args[i] = ExtensionLoader.getExtensionLoader(Serialization.class)
                                    .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                                    .deserialize(null, is).readObject();
                            } catch (Exception e) {
                                throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
                            }
                        } else {
                            throw new RpcException(
                                new StringBuilder(32).append("Generic serialization [")
                                    .append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                                    .append("] only support message type ")
                                    .append(byte[].class)
                                    .append(" and your message type is ")
                                    .append(args[i].getClass()).toString());
                        }
                    }
                }
                Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));
                if (result.hasException()
                        && ! (result.getException() instanceof GenericException)) {
                        /*********************和源码不一样的地方**********************/
                	if(result.getException() instanceof XXXException){
                        return new RpcResult(result.getException());
                	}else{
                		return new RpcResult(new GenericException(result.getException()));
                	}
                        /*********************和源码不一样的地方_结束**********************/
                }
                if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                    try {
                        UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
                        ExtensionLoader.getExtensionLoader(Serialization.class)
                            .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                            .serialize(null, os).writeObject(result.getValue());
                        return new RpcResult(os.toByteArray());
                    } catch (IOException e) {
                        throw new RpcException("Serialize result failed.", e);
                    }
                } else {
                    return new RpcResult(PojoUtils.generalize(result.getValue()));
                }
            } catch (NoSuchMethodException e) {
                throw new RpcException(e.getMessage(), e);
            } catch (ClassNotFoundException e) {
                throw new RpcException(e.getMessage(), e);
            }
        }
        return invoker.invoke(inv);
    }

}

当然不要忘记将filter配置到META-INF和spring的配置文件中,关于filter的配置见:dubbo配置filter隐式传参

当然此处也可以直接修改dubbo的源码,不过dubbo既然提供了filter能处理这个问题,最好还是不要去动源码了!

你可能感兴趣的:(dubbo,GenericService)