Reputation: 686
Im sending messages to a topic in pubsub with this script:
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path("my-project", "my-topic")
while True:
msg = b"some message"
future = publisher.publish(topic_path, msg)
try:
result = future.result()
except Exception as ex:
# handle exception
print(ex)
time.sleep(3)
My problem is how to make my print(ex)
to print when a message is not posted on pubsub or detect when message wasn't sent and try to post it again.
Upvotes: 0
Views: 2310
Reputation: 7277
You can check this article as it implemented error handling for publishing. A method was created for getting callbacks. It accepts future object and data string. If there is an exception, it will call exception() to return the raised exception.
def get_callback(f, data):
def callback(f):
try:
print(f.result())
futures.pop(data)
except: # noqa
print("Please handle {} for {}.".format(f.exception(), data))
return callback
This method was used to implement get_callback by passing the "future" and "data" parameters. Wherein future is a object and data is string.
for i in range(10):
data = str(i)
futures.update({data: None})
# When you publish a message, the client returns a future.
future = publisher.publish(topic_path, data.encode("utf-8"))
futures[data] = future
# Publish failures shall be handled in the callback function.
future.add_done_callback(get_callback(future, data))
# Wait for all the publish futures to resolve before exiting.
while futures:
time.sleep(5)
Upvotes: 1