1
1
#!/usr/bin/env python
2
2
3
- # Copyright 2016 Google Inc . All Rights Reserved.
3
+ # Copyright 2019 Google LLC . All Rights Reserved.
4
4
#
5
5
# Licensed under the Apache License, Version 2.0 (the "License");
6
6
# you may not use this file except in compliance with the License.
@@ -157,8 +157,8 @@ def publish_messages_with_futures(project_id, topic_name):
157
157
158
158
159
159
def publish_messages_with_error_handler (project_id , topic_name ):
160
- """Publishes multiple messages to a Pub/Sub topic with an error handler."""
161
160
# [START pubsub_publish_messages_error_handler]
161
+ """Publishes multiple messages to a Pub/Sub topic with an error handler."""
162
162
import time
163
163
164
164
from google .cloud import pubsub_v1
@@ -170,10 +170,8 @@ def publish_messages_with_error_handler(project_id, topic_name):
170
170
topic_path = publisher .topic_path (project_id , topic_name )
171
171
172
172
def callback (message_future ):
173
- # When timeout is unspecified, the exception method waits indefinitely.
174
- if message_future .exception (timeout = 30 ):
175
- print ('Publishing message on {} threw an Exception {}.' .format (
176
- topic_name , message_future .exception ()))
173
+ if message_future .exception ():
174
+ print ('{} needs handling.' .format (message_future .exception ()))
177
175
else :
178
176
print (message_future .result ())
179
177
@@ -183,12 +181,14 @@ def callback(message_future):
183
181
data = data .encode ('utf-8' )
184
182
# When you publish a message, the client returns a Future.
185
183
message_future = publisher .publish (topic_path , data = data )
184
+ # If you wish to handle publish failures, do it in the callback.
185
+ # Otherwise, it's okay to call `message_future.result()` directly.
186
186
message_future .add_done_callback (callback )
187
187
188
188
print ('Published message IDs:' )
189
189
190
- # We must keep the main thread from exiting to allow it to process
191
- # messages in the background.
190
+ # We keep the main thread from exiting so message futures can be
191
+ # resolved in the background.
192
192
while True :
193
193
time .sleep (60 )
194
194
# [END pubsub_publish_messages_error_handler]
0 commit comments