Không phải là một ý tưởng tồi để mở rộng NSError. Tôi cũng đã tạo một danh mục trên NSError
để sử dụng riêng của mình. Tôi muốn chia sẻ nó với bạn.
(1) Tạo một file strings
để xác định tất cả các mã lỗi:
/* 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) Thực hiện một loại trên NSError, chúng ta hãy nói "NSError + errorInfo":
@interface NSError (ErrorInfo)
-(NSString *)userDescription;
@end
(3) Xác định:
#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) Hãy sử dụng nó:
NSError *yourError; // This can be any NSError object you get
yourError = [NSError errorWithDomain:@"yourDomain" code:2000 userInfo:details]; // Just for test
NSLog(@"%@",[yourError userDescription]);
Tôi không thấy sự cần thiết vì 'NSError' cung cấp thuộc tính miền mà bạn có thể đặt thành bất kỳ giá trị tên miền cụ thể nào. Bạn nghĩ gì khi thêm vào một lớp con 'NSError'? – trojanfoe
Tôi cũng nghĩ như vậy. Nhưng hãy nói các tình huống như phơi bày thêm một số thông tin về lỗi. Có thể là một số chi tiết cụ thể về miền. – uiroshan
Một lần nữa, đã được bao phủ bởi 'NSError' bằng cách thêm các mục vào từ điển' userInfo'. – trojanfoe