Raising a server error to the client with grpc

There's a new method for this too, context.abort() - it'll actually raise an exception to terminate the RPC call:

grpc.ServicerContext.abort()


So at gRPC side someone can abort context using: grpc.ServicerContext.abort()

At client side (python):

try:
    result = {'msg', 'success'}
except grpc.RpcError as e:
    if e.code() == grpc.StatusCode.INVALID_ARGUMENT:
        result = {'msg', 'invalid arg error'}
    elif e.code() == grpc.StatusCode.ALREADY_EXISTS:
        result = {'msg', 'already exists error'}

Yes, there is a better way. You may change the status details using the ServicerContext.set_details method and you may change the status code using the ServicerContext.set_code method. I suspect that your servicer will look something like

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

.