如何根据protobuf grpc规范正确格式化响应对象

时间:2019-07-25 12:15:53

标签: protocol-buffers grpc grpc-node

我有以下protobuf定义:

service MyService {
    rpc ServiceMethod (ServiceMethodRequest) returns (ServiceMethodResponse) {}
}

message ServiceMethodRequest{
    string requestParam = 1;
}
message ServiceMethodResponse{
    Error error = 1;
    SomeObjectList data = 2;
}
message Error{
    string code = 1;
    string errorMessage = 2;
}

message SomeObject {
    string myobject = 1;
}
message SomeObjectList {
    repeated SomeObject myobjects = 1;
}

如您所见,我想返回格式化的响应,因此我的API具有一些标准化的响应方式。我这样格式化了响应(出于可读性的原因,它采用JSON格式):

{"error":{"code":"-1","errorMessage":""},"data":{"myobjects":[{"myobject":"some string"},{"myobject":"another string"}]}}

但是在客户端,我不断得到:

{ Error: 2 UNKNOWN: Unknown Error
    at Object.exports.createStatusError (.../node_modules/grpc/src/common.js:91:15)
    at Object.onReceiveStatus (.../node_modules/grpc/src/client_interceptors.js:1204:28)
    at InterceptingListener._callNext (.../node_modules/grpc/src/client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (.../node_modules/grpc/src/client_interceptors.js:618:8)
    at callback (.../node_modules/grpc/src/client_interceptors.js:845:24)
  code: 2,
  metadata: Metadata { _internal_repr: {}, flags: 0 },
  details: 'Unknown Error' }

当我尝试console.log响应对象时。

我在做什么错? 另外,是否有关于grpc的好书,并提供了一些示例(C,C#,Java,Python,JavaScript)? 预先感谢!

1 个答案:

答案 0 :(得分:-1)

server.js

callback(null, message);