Generally speaking, when an error occurs that prohibits an operation from succeeding, AMPS will throw an exception. AMPS exceptions universally derive from com.crankuptheamps.client.exception.AMPSException, so by catching AMPSException, you will be sure to catch anything AMPS throws. For example:
import com.crankuptheamps.client.Client;
import com.crankuptheamps.client.exception.AMPSException;
public void readAndEvaluate(Client client) {
Scanner scanner = new Scanner(System.in);
String payload = scanner.nextLine();
// write a new message to AMPS
if ( payload != null) {
try {
client.publish("UserMessage", " { \"data\" : \"" + payload + "\" }");
}
catch (AMPSException e) {
System.err.println("An AMPS exception occurred: " + e.toString());
e.printStackTrace();
}
}
}
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 stderr, which calls the exception's toString() method. As with most Java exceptions, toString() will convert the Exception into a string that includes a message. The printStackTrace() method will write to stderr the stack trace and information on any ”inner” exceptions (exceptions 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, 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;
string topicName;
while (id == null) {
/* Our program is an interactive program that attempts to retrieve a topic
* name (or regular expression) from the user.
*/
topicName = askUserForTopicName();
try {
Command command = new Command("subscribe").setTopic(topicName);
MessagePrinter mp = new MessagePrinter();
id = client.executeAsync(command, mp);
}
catch(BadRegexTopicException ex) {
/* This line indicates that the program catches the BadRegexTopicException
* 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 catch block, the while loop runs again and the user is asked for
* another topic name.
*/
System.err.println("Error: bad topic name " +
"or regular expression " + topicName +
". The error was: " + ex.toString());
// we’ll ask the user for another topic
}
catch(AMPSException ex) {
/* 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.
*/
System.err.println("Error: error setting " +
"up subscription to topic " +
topicName + ". The error was: " +
ex.toString());
return null; // give up
}
}
return id;
}