1、dubbo是一套远程rpc框架,那就存在两种角色,一是服务提供者,二是服务调用者;
服务提供者有时候需要throw异常,那这个时候客户端是否可以捕获,捕获的机制怎样;
- 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;
- }
- }
从代码中我们可以出各个流程;先判断异常是否是可捕获异常,是则直接抛出,再判断是否同一个包下面,是则抛出,再判断是否是jdk提供异常是则抛出,如果都不是则抛出dubbo自定义rpc异常;
看完源码以后,做出了新的设计,CommonException不变,各个接口模块(maven工程为单位)单独定义异常对象继承CommonException,每个模块抛出自己的模块异常(如用户模块抛出UicException),客户端中用CommonException统一捕获处理