Skip to content

Commit 3a8a6f1

Browse files
author
chenyumic
authored
Add the Pub/Sub handle_publisher_error sample [(#1440)](GoogleCloudPlatform/python-docs-samples#1440)
* Add the Pub/Sub handle_publisher_error sample * Update requirements.txt * Update publisher.py * Update publisher.py * Added region tag
1 parent 915f209 commit 3a8a6f1

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

samples/snippets/publisher.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"""
2323

2424
import argparse
25+
import concurrent.futures
2526

2627
from google.cloud import pubsub_v1
2728

@@ -123,6 +124,38 @@ def publish_messages_with_futures(project, topic_name):
123124
# [END pubsub_publisher_concurrency_control]
124125

125126

127+
def publish_messages_with_error_handler(project, topic_name):
128+
"""Publishes multiple messages to a Pub/Sub topic with an error handler."""
129+
# [START pubsub_publish_messages_error_handler]
130+
publisher = pubsub_v1.PublisherClient()
131+
topic_path = publisher.topic_path(project, topic_name)
132+
133+
# When you publish a message, the client returns a Future. This Future
134+
# can be used to track if an error has occurred.
135+
futures = []
136+
137+
def callback(f):
138+
exc = f.exception()
139+
if exc:
140+
print('Publishing message on {} threw an Exception {}.'.format(
141+
topic_name, exc))
142+
143+
for n in range(1, 10):
144+
data = u'Message number {}'.format(n)
145+
# Data must be a bytestring
146+
data = data.encode('utf-8')
147+
message_future = publisher.publish(topic_path, data=data)
148+
message_future.add_done_callback(callback)
149+
futures.append(message_future)
150+
151+
# We must keep the main thread from exiting to allow it to process
152+
# messages in the background.
153+
concurrent.futures.wait(futures)
154+
155+
print('Published messages.')
156+
# [END pubsub_publish_messages_error_handler]
157+
158+
126159
def publish_messages_with_batch_settings(project, topic_name):
127160
"""Publishes multiple messages to a Pub/Sub topic with batch settings."""
128161
# [START pubsub_publisher_batch_settings]

samples/snippets/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
google-cloud-pubsub==0.32.1
2+
futures==3.1.1; python_version < '3'

0 commit comments

Comments
 (0)