Getting server error to client using grpc

Consider a simple service:

service Something {
    rpc Do(Request) returns Response;
}

message Request {
    string field = 1;
}

message Response {
    string response = 1; 
}

Suppose I need to do some checking on Request.field, I want to raise a client error if the field is invalid:

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!")

With the following client:

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)

<_Rendezvous RPC that is completed (StatusCode.UNKNOWN, application to call Exception: Damn!)>

Therefore, I can technically handle errors. My problem ... is there a better way? Is there a good way to change the description of a message? Can we change the status code?

+4
source share
3 answers

, . , ServicerContext.set_details, ServicerContext.set_code. , servicer

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!')

.

+8

context.abort() - RPC:

grpc.ServicerContext.abort()

0

There is an article on how to handle grpc errors in different languages: gRPC Errors

0
source

Source: https://habr.com/ru/post/1662988/


All Articles