Generally speaking, when an error occurs that prohibits an operation from succeeding, AMPS will throw an exception. AMPS exceptions universally derive from AMPS.Client.Exceptions.AMPSException, so by catching AMPSException, you will be sure to catch anything AMPS throws, for example:
using AMPS.Client;
using AMPS.Client.Exceptions;
...
public static void ReadAndEvaluate(Client client)
{
// read a new payload from the user
string payload = Console.ReadLine();
// write a new message to AMPS
if (!string.IsNullOrEmpty(payload))
{
try
{
client.publish("UserMessage", @"{ ""data"" : """ + payload + @""" }");
}
catch (AMPSException exception)
{
Console.Error.WriteLine("An AMPS exception " +
"occurred: {0}", exception);
}
}
}
In this example, if an error occurs, the program writes the error to Console.Error 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, which implicitly calls the exception's ToString() method. As with most .NET exceptions, ToString() will convert the exception into a string that includes a message, stacktrace and information on any "inner" exceptions (exception from outside of AMPS that caused AMPS to throw an exception).
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, then you can catch the appropriate subclass of AMPSException to detect those specific errors and do something different.
public CommandId CreateNewSubscription(Client client)
{
CommandId id = null;
// Attempt to retrieve a topic name (or regular
// expression) from the user.
string topicName;
while (id == null)
{
topicName = AskUserForTopicName();
try
{
Command command = new Command("subscribe").setTopic(topicName);
// If an error occurs when setting up the subscription, whether or not to try
// again depends on the subclass of AMPSException that is thrown. If a
// BadRegexTopicException is thrown, it means that a bad regular expression was
// supplied during subscription. In this case, we would like to give the user a
// chance to correct the issue.
id = client.executeAsync(command, (x)=>HandleMessage(x));
}
catch(BadRegexTopicException ex)
{
DisplayError(string.Format("Error: bad topic name or regular " +
"expression '{0}'. The error was: {1}",
topicName,
ex.Message));
// we'll ask the user for another topic
}
// If an AMPS exception of a type other than BadRegexTopicException is thrown by
// AMPS, it is caught here. In that case, the program emits a different error
// message to the user.
catch(AMPSException ex)
{
DisplayError(string.Format("Error: error setting up subscription " +
"to topic '{0}'. The error was: {1}",
topicName,
ex.Message));
// At this point the code stops attempting to subscribe to the client by the return
// null statement.
return null; // give up
}
}
return id;
}