扩展 NSError 并不是一个坏主意。
我还在NSError 上创建了一个类别供我自己使用。我想和你分享。
(1)制作strings文件,定义所有错误码:
/* Following are general error messgaes those we can show to user
regarding to Internet connection and request. You can add more
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"; // custom created error code
/* Always describe unknow error with whatever you want in
except case (i.e. except error codes). If not mentioned
the following line, still you will get message "Unknown error" */
"Unknown error" = "Network error occured";
(2) 在 NSError 上做一个分类,比如说“NSError+ErrorInfo”:
@interface NSError (ErrorInfo)
-(NSString *)userDescription;
@end
(3) 定义它:
#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) 使用它:
NSError *yourError; // This can be any NSError object you get
yourError = [NSError errorWithDomain:@"yourDomain" code:2000 userInfo:details]; // Just for test
NSLog(@"%@",[yourError userDescription]);