From 464500fda407ee52b378b322d3ac8bd531329d87 Mon Sep 17 00:00:00 2001 From: noerog <32459203+noerog@users.noreply.github.com> Date: Mon, 8 Jan 2018 17:16:12 -0500 Subject: [PATCH] Add listen for errors sample. [(#1306)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1306) * Add listen for errors sample. * Update subscriber.py * Update subscriber.py --- samples/snippets/subscriber.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/samples/snippets/subscriber.py b/samples/snippets/subscriber.py index 9dded25b1..577e77cb9 100644 --- a/samples/snippets/subscriber.py +++ b/samples/snippets/subscriber.py @@ -110,6 +110,30 @@ def callback(message): time.sleep(60) +def listen_for_errors(project, subscription_name): + """Receives messages and catches errors from a pull subscription.""" + subscriber = pubsub_v1.SubscriberClient() + subscription_path = subscriber.subscription_path( + project, subscription_name) + + def callback(message): + print('Received message: {}'.format(message)) + message.ack() + + subscription = subscriber.subscribe(subscription_path, callback=callback) + + # Blocks the thread while messages are coming in through the stream. Any + # exceptions that crop up on the thread will be set on the future. + future = subscription.open(callback) + try: + future.result() + except Exception as e: + print( + 'Listening for messages on {} threw an Exception: {}.'.format( + subscription_name, e)) + raise + + if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, @@ -143,6 +167,10 @@ def callback(message): help=receive_messages_with_flow_control.__doc__) receive_with_flow_control_parser.add_argument('subscription_name') + listen_for_errors_parser = subparsers.add_parser( + 'listen_for_errors', help=listen_for_errors.__doc__) + listen_for_errors_parser.add_argument('subscription_name') + args = parser.parse_args() if args.command == 'list_in_topic': @@ -160,3 +188,5 @@ def callback(message): elif args.command == 'receive-flow-control': receive_messages_with_flow_control( args.project, args.subscription_name) + elif args.command == 'listen_for_errors': + listen_for_errors(args.project, args.subscription_name)