Generally speaking, when an error occurs that prohibits an operation from succeeding, AMPS will throw an exception. AMPS exceptions universally derive from AMPS.AMPSException, so by catching AMPSException, you will be sure to catch anything AMPS throws, for example:
def read_and_evaluate(client):
# read a new payload from the user
payload = input("Please enter a message")
# write a new message to AMPS
if payload:
try:
client.publish(
"UserMessage",
"{ \"message\" : \"%s\" }" % payload
)
except AMPS.AMPSException as e:
sys.stderr.write("An AMPS exception" + "occurred: %s" % str(e))
In this example, if an error occurs, the program writes the error to stderr and the publish() command fails. However, client is still usable for continued publishing and subscribing. When the error occurs, the exception is written to the console. As with most Python exceptions, str() will convert the exception into a string that includes a descriptive message.
AMPS exception types vary based on the nature of the error that occurs. In your program, if you would like to handle certain kinds of errors differently than others, you can handle the appropriate subclass of AMPSException to detect those specific errors and do something different.
def create_new_subscription(client):
messageStream = None
topicName = None
while messageStream is None:
# attempts to retrieve a topic name (or regular expression) from the user.
topicName = input("Please enter a topic name")
try:
# If an error occurs when setting up the subscription, the program decides whether
# or not to try again based on the subclass of AMPSException that is thrown. In
# this case, if the exception is a BadRegexTopicError, the exception indicates
# that the user provided a bad regular expression. We would like to give the user
# a chance to correct, so we ask the user for a new topic name.
messageStream = client.subscribe(
topicName,
None
)
# This line indicates that the program catches the BadRegexTopicError exception
# and displays a specific error to the user indicating the topic name or
# expression was invalid. By not returning from the function in this except block,
# the while loop runs again and the user is asked for another topic name.
except BadRegexTopicError as e:
print(
"Error: bad topic name or regular expression " +
topicName +
". The exception was " +
str(e) +
"."
)
# we'll ask the user for another topic
# If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
# it is caught here. In that case, the program emits a different error message to
# the user.
except AMPSException as e:
print (
"Error: error setting up subscription to topic" +
topicName +
". The exception was " +
str(e) +
"."
)
# At this point the code stops attempting to subscribe to the client by the return
# None statement.
return None
return messageStream