How to return a gRPC status code?


I’ve followed this guide to setup a gRPC server: Set Up a gRPC Service — Ray 2.7.0

Now I’m wondering how I can return a gRPC status code back to the client? Usually in Python you are provided with a context object with each request that can be used to set/return a status code that is passed back to the client.

Hi Homer,

Thanks for trying out our new gRPC feature! Context is usually used on the server side. Client side you will be getting a call object back from the server containing the status code and the message. There are examples in the same doc you linked looks like the following

import grpc
from user_defined_protos_pb2_grpc import UserDefinedServiceStub
from user_defined_protos_pb2 import UserDefinedMessage

channel = grpc.insecure_channel("localhost:9000")
stub = UserDefinedServiceStub(channel)
request = UserDefinedMessage(name="foo", num=30, origin="bar")

response, call = stub.__call__.with_call(request=request)
print(f"status code: {call.code()}")  # grpc.StatusCode.OK
print(f"greeting: {response.greeting}")  # "Hello foo from bar"
print(f"num: {response.num}")  # 60

Noted that when you use with_call(), the call object for the request will be returned to you.

Also make sure you also check out the Handle errors section as if the request errors out, the status code would be embedded in the error.