Search code examples
pythonexceptiongrpcrpc

How to handle custom exceptions with gRPC in Python?


I need to implement custom exceptions for handling gRPC request errors with Python. For HTTP requests it's straightforward - requests library catches it well when there's an error code etc. I am looking for analogous ways for gRPC to do something like:

try:
    # send gRPC request
except SomeGRPCException as e:
    # custom handle

Is there a way to handle gRPC errors like that in Python? Or with gRPC it wouldn't work like in the example?


Solution

  • For simple RPC error handling, you can use try-catch:

    try:
        response = stub.SayHello(...)
    except grpc.RpcError as rpc_error:
        if rpc_error.code() == grpc.StatusCode.CANCELLED:
            pass
        elif rpc_error.code() == grpc.StatusCode.UNAVAILABLE:
            pass
        else:
            print(f"Received unknown RPC error: code={rpc_error.code()} message={rpc_error.details()}")
    

    For complex RPC error handling, you may need to utilize the trailing metadata: https://github.com/grpc/grpc/tree/master/examples/python/errors

    In most cases, try-catch should be sufficient.