You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
gRPC errors in Python are raised as grpc.RpcError exceptions. Here's how to handle them:
importgrpctry:
response=awaitself._stub.GetMicrogridDispatch(request)
# Process the successful response hereexceptgrpc.RpcErroraserror:
status_code=error.code() # Get the gRPC status codedetails=error.details() # Optional error details as a string # Example of handling based on status codeifstatus_code==grpc.StatusCode.NOT_FOUND:
print("Resource not found!")
elifstatus_code==grpc.StatusCode.PERMISSION_DENIED:
print("Insufficient permissions")
else:
print(f"Error occurred: {status_code} - {details}")
Proposed solution
Add wrapper error classes for the relevant gRPC errors raised by clients.
Some of these errors should inherit from specific Python built-in errors, like INVALID_ARGUMENT should inherit from ValueError, NOT_FOUND and ALREADY_EXISTS should probably inherit from KeyError, etc.
For errors that should never occur (because the client is doing some sanity checks to prevent them from happening), we should probably still have a wrapper in the client, like UnexpectedError, because a server could always misbehave for some reason.
When raising these errors in the client, we can still attach the original gRPC error using the raise OurClientError(...) from grpc_error syntax, which could be very useful for debugging purposes.
What's needed?
We need to make sure gRPC errors are properly wrapped so we don't leak the use of grpc/protobuf to client users.
From frequenz-floss/frequenz-api-dispatch#144:
gRPC errors in Python are raised as
grpc.RpcError
exceptions. Here's how to handle them:Proposed solution
Add wrapper error classes for the relevant gRPC errors raised by clients.
Some of these errors should inherit from specific Python built-in errors, like
INVALID_ARGUMENT
should inherit fromValueError
,NOT_FOUND
andALREADY_EXISTS
should probably inherit fromKeyError
, etc.For errors that should never occur (because the client is doing some sanity checks to prevent them from happening), we should probably still have a wrapper in the client, like
UnexpectedError
, because a server could always misbehave for some reason.When raising these errors in the client, we can still attach the original gRPC error using the
raise OurClientError(...) from grpc_error
syntax, which could be very useful for debugging purposes.Additional context
The text was updated successfully, but these errors were encountered: