Thursday, January 07, 2010

Handling iPhone errors part two

Now that I can make a pop-up message I wanted to clean up the code and do all of my error processing from one place. To this end I removed all of the error handling I was doing and instead changed it so my individual functions would return a value. The number 0 if everything was ok, and a number that would signify the error type if everything was not ok. I had about 15 possible errors at the time so I gave them all numbers and converted my functions from -(void) to -(int) and added the numbers to the return lines. Below you will see an example of the code and how I'm now processing the errors. Everything works fine, but if there is a better way to do this, please let me and everyone else know.

// Header file

- (IBAction)refreshInformation:(id)sender;

- (int)verifyUserInput;

- (void)handleErrors:(int)errorNumber;

// Call the function to check user input, and then pass the results to the error checking //function

- (IBAction)refreshInformation:(id)sender {

NSInteger funcReturn = 0;

// Verify they have entered everything we need to get the information

funcReturn = [self verifyUserInput];

// Did we have any errors?

if (funcReturn) {

[self handleErrors:funcReturn];



// Function to check the user input

- (int)verifyUserInput {

// Initialize some local variables with the input from the user

NSString *nameString = userName.text;

NSString *passString = userPassword.text;

NSString *serverString = serverAddress.text;

// Verify that people are putting the right stuff into the fields

if ([nameString length] == 0) {

return 11;

} else if ([passString length] == 0) {

return 11;

} else if ([serverString length] == 0) {

return 11;


return 0;


// Function to process the error numbers

- (void)handleErrors:(int)errorNumber {

NSString *errorText;

switch (errorNumber) {

case 11:

errorText = @"All fields are required";


case 21:

errorText = @"Authentication failed";


case 22:

errorText = @"System login failure";


case 23:

errorText = @"Read-Only user required";


case 24:

errorText = @"Network connection failed";



UIAlertView *error = [[UIAlertView alloc] initWithTitle:[[NSString alloc] initWithFormat:@"Error: %D", errorNumber]

message:[[NSString alloc] initWithFormat:@"%@", errorText]



otherButtonTitles: nil];

[error show];

[error release];


No comments: