thrift:返回null的解决办法

最的项目用到swift:thrift做RPC框架,开始也没有了解太深,就开始干了,今天开始测试了,发现thrift居然不允许服务接口返回null。跟踪源码到下面的方法,找到为null时抛出异常的位置:

Object com.facebook.swift.service.ThriftMethodHandler.readResponse(TProtocol in) throws Exception

readResponse方法片段:

        if (successCodec.getType() == ThriftType.VOID) {
            // TODO: check for non-null return from a void function?
            return null;
        }

        if (results == null) {
            throw new TApplicationException(TApplicationException.MISSING_RESULT, name + " failed: unknown result");
            // result为null抛出异常,异常错误代码:TApplicationException.MISSING_RESULT
        }

知道原因就好解决了,捕获TApplicationException异常判断就可以了:

    public List loadAllPerson(){
        try{
            return service.loadAllPerson();
        }
        // 捕获RuntimeTApplicationException异常
        catch(RuntimeTApplicationException e){
            Throwable cause = e.getCause();
            // cause 类型为 TApplicationException时再判断异常类型时是否为MISSING_RESULT,
            // 是就返回null,否则继续向上抛出
            if (cause instanceof TApplicationException  
                && ((TApplicationException) cause).getType() == TApplicationException.MISSING_RESULT){
                return null;
            }
            throw e;
        }
        catch(net.gdface.facelog.client.thrift.ServiceRuntime e){
            throw new ServiceRuntime(e);
        }
    }

你可能感兴趣的:(java)