2016-12-06 85 views
4

讓我們考慮一個簡單的服務:提高了服務器錯誤到客戶端GRPC

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) 
RPC的210個

< _Rendezvous與(StatusCode.UNKNOWN,異常調用的應用程序:媽的!)終止>

所以我可以在技術上處理錯誤。我的問題是......有更好的方法嗎?有沒有改變消息描述的好方法?我們可以更改狀態碼嗎?

回答

7

是的,還有更好的辦法。您可以使用ServicerContext.set_details方法更改狀態詳細信息,也可以使用ServicerContext.set_code方法更改狀態代碼。我懷疑你的服務員看起來像

class MyService(proto_pb2.SomethingServicer): 

    def Do(self, request, context): 
     if not is_valid_field(request.field): 
      context.set_code(grpc.StatusCode.INVALID_ARGUMENT) 
      context.set_details('Consarnit!') 
      return proto_pb2.Response() 
     return proto_pb2.Response(response='Yeah!') 

+1

很酷,感謝您的答案!你介意爲記錄添加一個小客戶的例子嗎?抱歉,遲到的接受:) – FunkySayu

+0

我不願意爲這種情況添加客戶端示例代碼,因爲服務器在這種情況下通信的是「您,客戶端有bug」。而不是增強客戶端代碼來處理服務器的響應,客戶端代碼中的錯誤應該簡單地修復。對? –

+1

也許客戶端有一個bug,或者客戶端得到了一些不知道如何完全驗證的用戶輸入。在任何情況下,如果能夠顯示客戶端上的「代碼」和「細節」如何被檢查,答案將會更有價值。 –

0

有一個關於如何處理GRPC錯誤文章在各種語言: gRPC Errors

+0

鏈接本身不被視爲答案。 – sg7

相關問題