我想说正确的方法是NSError
在所有可能出错的方法中直接使用自己。我最近使用我创建的实用程序类完成了此操作,并且效果很好。然后,您允许应用程序决定如何处理错误(崩溃、日志、其他内容),并且框架无需担心。
以下是我用来创建错误对象的私有errno
类方法,允许潜在的 POSIX 错误(等):
#pragma mark - Private Methods
- (NSError *)error:(NSString *)localizedDescription
code:(EZipFileError)code
underlyingError:(NSError *)underlyingError
{
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:localizedDescription forKey:NSLocalizedDescriptionKey];
if (underlyingError != nil)
{
[errorDetail setValue:underlyingError forKey:NSUnderlyingErrorKey];
}
return [NSError errorWithDomain:@"MyErrorDomain"
code:(NSInteger)code
userInfo:errorDetail];
}
- (NSError *)error:(NSString *)localizedDescription
code:(EZipFileError)code
{
return [self error:localizedDescription
code:code
underlyingError:nil];
}
- (NSError *)error:(NSString *)localizedDescription
code:(EZipFileError)code
posixError:(int)posixError
{
NSMutableDictionary *underlyingErrorDetail = [NSMutableDictionary dictionary];
[underlyingErrorDetail setValue:[NSString stringWithUTF8String:strerror(posixError)]
forKey:NSLocalizedDescriptionKey];
NSError *underlyingError = [NSError errorWithDomain:NSPOSIXErrorDomain
code:posixError
userInfo:underlyingErrorDetail];
return [self error:localizedDescription
code:code
underlyingError:underlyingError];
}
使用如下:
if (![self isOpen])
{
if (error != NULL)
{
*error = [self error:@"File is not open"
code:ErrorNotOpen];
}
return nil;
}
这是一个使用该方法的底层 POSIX 错误版本的示例:
filefp = fopen([filename UTF8String], "rb");
if (filefp == NULL)
{
if (error != NULL)
{
*error = [self error:@"Failed to open file"
code:ErrorOpenFileFailed
posixError:errno];
}
return NO;
}