Skip to content

Add listen for errors sample. #1306

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 8, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions pubsub/cloud-client/subscriber.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,34 @@ 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):
try:
print('Received message: {}'.format(message))
message.ack()
future.result()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldreplace lines 136-138 with the try: future.result() except: ....

except Exception as e:
print(
'Listening for messages on {} threw an Exception: {}.'.format(
subscription_name, e))
subscription.close()
raise

subscription = subscriber.subscribe(subscription_path, callback=callback)
future = subscription.open(callback)

# The subscriber is non-blocking, so we must keep the main thread from
# exiting to allow it to process messages in the background.
print('Listening for messages and errors on {}'.format(subscription_path))
while True:
time.sleep(60)


if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
Expand Down Expand Up @@ -143,6 +171,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':
Expand All @@ -160,3 +192,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)