简体   繁体   English

如何在 Python 中使用 gRPC 处理自定义异常?

[英]How to handle custom exceptions with gRPC in Python?

I need to implement custom exceptions for handling gRPC request errors with Python.我需要实现自定义异常以使用 Python 处理 gRPC 请求错误。 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:对于 HTTP 请求,它很简单 - requests 库在出现错误代码等时可以很好地捕获它。我正在寻找 gRPC 执行以下操作的类似方法:

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

Is there a way to handle gRPC errors like that in Python?有没有办法在 Python 中处理像这样的 gRPC 错误? Or with gRPC it wouldn't work like in the example?或者使用 gRPC 它不会像示例中那样工作?

For simple RPC error handling, you can use try-catch:对于简单的 RPC 错误处理,您可以使用 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对于复杂的 RPC 错误处理,您可能需要利用尾随元数据:https ://github.com/grpc/grpc/tree/master/examples/python/errors

In most cases, try-catch should be sufficient.大多数情况下,try-catch 就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM