8

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?

Eli Halych
  • 545
  • 7
  • 25
  • The code looks fine. You just have to import the exception. – Klaus D. Oct 28 '20 at 08:40
  • @KlausD. Is there any library for gRPC like 'requests' for HTTP that will handle different situations? I might catch those predefined exception by that specific library and then raise my custom exception in the except block. What do you think? – Eli Halych Oct 28 '20 at 08:48

1 Answers1

15

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.

Lidi Zheng
  • 1,801
  • 8
  • 13
  • It looks like `grpc.RpcError` doesn't actually declare that method `.code()` (or any methods). Only the subclasses in gRPC do (e.g. `_InactiveRpcError`), so I've imported `from grpc._channel import _InactiveRpcError`, and then I can `assert rpc_error.code() == grpc.StatusCode.FAILED_PRECONDITION` – Ben Butterworth Nov 23 '22 at 10:13