Debian Codegraph @

examples/python/errors/client.py

raw
1 # Copyright 2019 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """This example handles rich error status in client-side."""
15
16 from __future__ import print_function
17
18 import logging
19
20 from google.rpc import error_details_pb2
21 import grpc
22 from grpc_status import rpc_status
23
24 from examples.protos import helloworld_pb2
25 from examples.protos import helloworld_pb2_grpc
26
27 _LOGGER = logging.getLogger(__name__)
28
29
30 def process(stub):
31 try:
32 response = stub.SayHello(helloworld_pb2.HelloRequest(name='Alice'))
33 _LOGGER.info('Call success: %s', response.message)
34 except grpc.RpcError as rpc_error:
35 _LOGGER.error('Call failure: %s', rpc_error)
36 status = rpc_status.from_call(rpc_error)
37 for detail in status.details:
38 if detail.Is(error_details_pb2.QuotaFailure.DESCRIPTOR):
39 info = error_details_pb2.QuotaFailure()
40 detail.Unpack(info)
41 _LOGGER.error('Quota failure: %s', info)
42 else:
43 raise RuntimeError('Unexpected failure: %s' % detail)
44
45
46 def main():
47 # NOTE(gRPC Python Team): .close() is possible on a channel and should be
48 # used in circumstances in which the with statement does not fit the needs
49 # of the code.
50 with grpc.insecure_channel('localhost:50051') as channel:
51 stub = helloworld_pb2_grpc.GreeterStub(channel)
52 process(stub)
53
54
55 if __name__ == '__main__':
56 logging.basicConfig()
57 main()