美文网首页程序员
记一次Dubbo的异常处理

记一次Dubbo的异常处理

作者: 谁说咖啡不苦 | 来源:发表于2019-03-10 21:54 被阅读0次

Dubbo的异常处理

最近项目中在使用到泛化的网关处理。这里分享一下,在调用的过程中,Dubbo对异常的处理。

官方建议

首先我们来看看官方对异常处理的建议:

  • 建议使用异常汇报错误,而不是返回错误码,异常信息能携带更多信息,以及语义更友好。
  • 如果担心性能问题,在必要的时候,可以通过override掉异常类的filllnStackTrace()方法,使其不拷贝栈信息。
  • 查询方法不建议抛出checked异常,否则调用方在查询时将过多的try...catch, 并且不能进行有效处理。
  • 服务提供方不应将DAO或者SQL等异常抛出给消费者,应在服务实现中对消费方不关心的异常进行包装,否则可能出现消费方无法反序列化异常。

这里我们直接就进入主题。

Dubbo对异常的处理流程
Consumer方

在服务调用方这边,我这里只说明通过泛化调用的处理.
Dubbo进行泛化调用主要通过GenericService接口服务实现。
这里也不做泛化的调用说明。
服务调用方在处理的时候,通过泛化的Filter实现,这里也是通过SPI机制处理

generic=com.alibaba.dubbo.rpc.filter.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中,这个时候,我们在进行异常捕获分析的时候,紧要进行类似如下的操作:

// Provider抛出自定义异常InvokeParamsException。
try {
} catch(GenericException e) {
  if (x.getExceptionClass().equals(InvokeParamsException.class.getName()) {
    // 处理已定义异常流程
  }
}

这样的话,我们就能精准的定位到具体异常,然后做该做的事。

Provider方

在提供方进行处理的时候,这里就要引入ExceptionFilter

@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;
                    }
                    // 是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;
        }
    }
}

这一块的服务提供方对异常的处理代码也比较直观。这个异常处理的Filter还是通过SPI技术,链式的加入到流程中进行处理。这里的SPI的引入可以参看Dubbo的源码包下的META-INF下的dubbo.internal中的com.alibaba.dubbo.rpc.Filter文件,这里面定义了对应的处理Filter实现,如exception, generice, genericeImpl,而我们的Provider的异常处理,刚好对应的是

exception=com.alibaba.dubbo.rpc.filter.ExceptionFilter

如果想要详细了解SPI的原理,参考: Dubbo剖析-增强SPI的实现
服务提供方在处理的过程中,如果产生了异常,在AbstractInvoke中,对异常进行封装到RpcResult中。

try {
            return doInvoke(invocation);
        } catch (InvocationTargetException e) { // biz exception
            Throwable te = e.getTargetException();
            if (te == null) {
                return new RpcResult(e);
            } else {
                if (te instanceof RpcException) {
                    ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION);
                }
                return new RpcResult(te);
            }
        } catch (RpcException e) {
            if (e.isBiz()) {
                return new RpcResult(e);
            } else {
                throw e;
            }
        } catch (Throwable e) {
            return new RpcResult(e);
        }

public RpcResult(Throwable exception){
        this.exception = exception;
    }

这样,我们产生了异常,并且接口的实现不是基于GenericService处理的,这样我们就能往下走。
下面流程中,都是对异常的信息,进行一个判断,以便不需要在最后进行一个对异常的二次封住。这里我总结一下异常不需要进行封装成RuntimeException的情况。

  • 如果是checked异常,直接抛出
  • 在方法签名上有声明,直接抛出
  • 在方法签名上有声明,直接抛出
  • 是JDK自带的异常,直接抛出
  • 是Dubbo本身的异常,直接抛出

否则,包装成RuntimeException抛给客户端。而之所以包装成RuntimeException是为了在服务调用方在反序列化的时候,能够正常反序列化出对象信息。
这里尤其要注意封装成RuntimeException的时候,如果我们不注意,在服务调用方进行try...catch的时候,就会捕获不到异常,导致信息的丢失。

总结

Dubbo在服务提供方和服务调用方,走的两个异常的处理流程就是ExceptionFilter和GenericFilter,明报到两个Filter的内部处理流程对于异常的处理就简单明了。

相关文章

网友评论

    本文标题:记一次Dubbo的异常处理

    本文链接:https://www.haomeiwen.com/subject/zctmpqtx.html