Created
December 16, 2021 18:20
-
-
Save sebnyberg/b6b9301efede4c51fe4d1d48d694af81 to your computer and use it in GitHub Desktop.
Unsafe parsing of error details (trailing metadata) from client-side in GRPC Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def maybe_parse_details(e: grpc.RpcError) -> any: | |
if "_state" not in e.__dict__ or "trailing_metadata" not in e._state.__dict__: | |
return None | |
md = dict(e._state.trailing_metadata) | |
if "grpc-status-details-bin" not in md: | |
return None | |
val = md["grpc-status-details-bin"] | |
status = status_pb2.Status.FromString(val) | |
if len(status.details) != 1: | |
return None | |
details = status.details[0] | |
if details.Is(error_details_pb2.BadRequest.DESCRIPTOR): | |
msg = error_details_pb2.BadRequest() | |
details.Unpack(msg) | |
return msg | |
try: | |
req = user_pb.CreateUserRequest() | |
resp = user_stub.CreateUser(req) | |
except grpc.RpcError as e: | |
print(e) | |
details = maybe_parse_details(e) | |
if details: | |
print(details) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment