11#!/usr/bin/env python
22
3- # Copyright 2016 Google Inc . All Rights Reserved.
3+ # Copyright 2019 Google LLC . All Rights Reserved.
44#
55# Licensed under the Apache License, Version 2.0 (the "License");
66# 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):
157157
158158
159159def publish_messages_with_error_handler (project_id , topic_name ):
160- """Publishes multiple messages to a Pub/Sub topic with an error handler."""
161160 # [START pubsub_publish_messages_error_handler]
161+ """Publishes multiple messages to a Pub/Sub topic with an error handler."""
162162 import time
163163
164164 from google .cloud import pubsub_v1
@@ -170,10 +170,8 @@ def publish_messages_with_error_handler(project_id, topic_name):
170170 topic_path = publisher .topic_path (project_id , topic_name )
171171
172172 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 ()))
177175 else :
178176 print (message_future .result ())
179177
@@ -183,12 +181,14 @@ def callback(message_future):
183181 data = data .encode ('utf-8' )
184182 # When you publish a message, the client returns a Future.
185183 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.
186186 message_future .add_done_callback (callback )
187187
188188 print ('Published message IDs:' )
189189
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.
192192 while True :
193193 time .sleep (60 )
194194 # [END pubsub_publish_messages_error_handler]
0 commit comments