让我们考虑一个简单的服务:
service Something {
rpc Do(Request) returns Response;
}
message Request {
string field = 1;
}
message Response {
string response = 1;
}
假设我必须对 Request.field
进行一些检查,如果该字段无效,我想引发客户端错误:
class MyService(proto_pb2.SomethingServicer):
def Do(self, request, context):
if not is_valid_field(request.field):
raise ValueError("Damn!") # Or something like that
return proto_pb2.Response(response="Yeah!")
与以下客户:
channel = grpc.insecure_channel(...)
stub = proto_pb2.SomethingStub(channel)
try:
response = stub.Do(proto_pb2.Request(field="invalid"))
except grpc.RpcError as e:
print(e)
<_以(StatusCode.UNKNOWN,异常调用应用程序:该死的!)终止的 RPC 会合点>
所以我可以在技术上处理错误。我的问题是……有更好的方法吗?有什么好的方法可以更改消息描述?我们可以更改状态代码吗?
原文由 FunkySayu 发布,翻译遵循 CC BY-SA 4.0 许可协议
是的,有更好的方法。您可以使用
ServicerContext.set_details
ServicerContext.set_code
更改状态代码。我怀疑您的服务人员看起来像.