Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Eli Halych Avatar asked Apr 20 '26 14:04

Eli Halych


1 Answers

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.

like image 119
Lidi Zheng Avatar answered Apr 23 '26 04:04

Lidi Zheng