Microsoft/thrifty:RPC方法返回NULL的异常处理

33 篇文章 0 订阅
16 篇文章 1 订阅

我们知道:thrift框架是不允许返回值为null的,如果返回值为null,client端会抛出异常,我在之前用facebook/swift框架时就遇到了这个问题,这是当时解决问题的记录《thrift:返回null的解决办法》,现在使用Microsoft/thrifty框架实现的客户端同样也存在这个问题。
下面是thifty-compiler生成的client端存根代码的receive方法的部分片段:

    @Override
    protected PersonBean receive(Protocol protocol, MessageMetadata metadata) throws Exception {
      PersonBean result = null;
      .......
      if (result != null) {
        return result;
      } else if (ex1 != null) {
        throw ex1;
      } else {
        throw new ThriftException(ThriftException.Kind.MISSING_RESULT, "Missing result");
      }
    }
  }

可以看到,返回结果为null时,会抛出类型为MISSING_RESULTThriftException异常。
知道了原因,解决问题的方法有了:

		/**
		* 当前调用的回调函数,由当前接口方法设置
		*/
		final ServiceMethodCallback<Integer> callback = null;
		/** 创建一个侦听器对象,用于检测socket关闭状态 */
		final AsyncClientBase.Listener closeListener = new AsyncClientBase.Listener(){
		   @Override
		   public void onTransportClosed() {
		   }
		
		   @Override
		   public void onError(Throwable error) {
		       // 如果关闭时有异常,则将异常转给callback对象,
		       // 当方法返回值为null时抛出的ThriftException异常会在这里被拦截发给callback对象
		       callback.onError(error);
		   }        
		};
		
        SocketTransport transport = new SocketTransport.Builder(host,port).build();
        transport.connect();
        Protocol protocol = new BinaryProtocol(transport);
        /* force set private field 'strictWrite' to true */
        Field field = BinaryProtocol.class.getDeclaredField("strictWrite");
        field.setAccessible(true);
        field.set(protocol, true);
        // 创建client端接口实例
        final mypackage.MyPrjClient service = new mypackage.MyPrjClient(protocol,closeListener);
        
        // 创建callback对象
		callback = new ServiceMethodCallback<Integer>(){
	        @Override
	        public void onSuccess(Integer result) {
	            // do something       
	            try {
	            	// 关闭连接
	                service.close();
	            } catch (IOException e) {
	            }
	        }
	
	        @Override 
	        public void onError(Throwable error) {
	        	// 对象ThriftException异常,判断类型是否为MISSING_RESULT,是则调用onSuccess正常返回null       
	            if(error instanceof ThriftException ){
	                if(((ThriftException)error).kind == ThriftException.Kind.MISSING_RESULT  ){
	                    this.onSuccess(null);
	                }
	            }
	            // do something
	            try {
	                // 关闭连接
	                service.close();
	            } catch (IOException e) {
	            }
	        }};
	    // 执行异步接口调用
        service.callMethod(123,callback);        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值