Nice idea to extend an NSError. I also made a category on NSError for my own use. I would like to share it with you.
(1) Create a strings file to determine all error codes:
"-1001" = "Connection time out"; "-1003" = "Cannot find Host"; "-1004" = "Cannot connect to Host"; "-1005" = "Server is temporarily down"; "-1009" = "The Internet connection appears to be offline"; "-1012" = "Authentication failed"; "2000" = "This is a custom error message";
(2) Create a category in NSError, say, "NSError + ErrorInfo":
@interface NSError (ErrorInfo) -(NSString *)userDescription; @end
(3) Define this:
#define ERROR_KEY(code) [NSString stringWithFormat:@"%d",code] #define ERROR_LOCALIZED_DESCRIPTION(code) NSLocalizedStringFromTable(ERROR_KEY(code),@"Errors",nil) @implementation NSError (ErrorInfo) -(NSString *)userDescription { NSString *errorDescrption = NSLocalizedStringFromTable(ERROR_KEY(self.code),@"Errors",nil); if (!errorDescrption || [errorDescrption isEqual:ERROR_KEY(self.code)]){ return NSLocalizedStringFromTable(@"Unknown error",@"Errors",nil);; } else{ return ERROR_LOCALIZED_DESCRIPTION(self.code); } return nil; } @end
(4) Use it:
NSError *yourError; // This can be any NSError object you get yourError = [NSError errorWithDomain:@"yourDomain" code:2000 userInfo:details]; // Just for test NSLog(@"%@",[yourError userDescription]);
Nspratik
source share