关于ios:如何在iPhone应用程序中使用NSError?

How can I use NSError in my iPhone App?

我正在努力捕获应用程序中的错误,并且正在考虑使用NSError。 我对如何使用它以及如何填充它感到有些困惑。

有人可以提供一个示例说明我如何填充然后使用NSError吗?


好吧,我通常要做的是使我的方法在运行时可能出错,并引用NSError指针。如果该方法确实存在问题,则可以使用错误数据填充NSError引用,并从该方法返回nil。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
    return YES;
}

然后我们可以使用这种方法。除非该方法返回nil,否则甚至不必费心检查错误对象:

1
2
3
4
5
6
7
8
9
// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

我们能够访问错误的localizedDescription,因为我们为NSLocalizedDescriptionKey设置了一个值。

有关更多信息的最佳位置是Apple的文档。真的很好。

关于可可粉是我的女朋友,还有一个很好的简单教程。


我想根据我的最新实现添加更多建议。我看过苹果公司的一些代码,我认为我的代码行为大致相同。

上面的帖子已经解释了如何创建NSError对象并返回它们,因此我不会理会该部分。我将尝试建议一种在您自己的应用程序中集成错误(代码,消息)的好方法。

我建议创建1个标头,该标头将概述您域中的所有错误(即应用程序,库等)。我当前的标题如下:

FSError.h

1
2
3
4
5
6
7
8
9
FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;

enum {
    FSUserNotLoggedInError = 1000,
    FSUserLogoutFailedError,
    FSProfileParsingFailedError,
    FSProfileBadLoginError,
    FSFNIDParsingFailedError,
};

FSError.m

1
2
3
#import"FSError.h"

NSString *const FSMyAppErrorDomain = @"com.felis.myapp";

现在,当使用上述错误值时,Apple将为您的应用创建一些基本的标准错误消息。可能会产生如下错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
    FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
    if (profileInfo)
    {
        /* ... lots of parsing code here ... */

        if (profileInfo.username == nil)
        {
            *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];            
            return nil;
        }
    }
    return profileInfo;
}

苹果公司为上述代码生成的标准错误消息(error.localizedDescription)如下所示:

Error Domain=com.felis.myapp Code=1002"The operation couldn’t be completed. (com.felis.myapp error 1002.)"

上面的内容对于开发人员已经非常有用,因为该消息显示了发生错误的域和相应的错误代码。最终用户将不知道错误代码1002意味着什么,因此现在我们需要为每个代码实现一些不错的消息。

对于错误消息,我们必须牢记本地化(即使我们没有立即实施本地化的消息)。我在当前项目中使用了以下方法:

1)创建一个将包含错误的strings文件。字符串文件很容易本地化。该文件可能如下所示:

FSError.strings

1
2
3
4
5
"1000" ="User not logged in.";
"1001" ="Logout failed.";
"1002" ="Parser failed.";
"1003" ="Incorrect username or password.";
"1004" ="Failed to parse FNID."

2)添加宏以将整数代码转换为本地化的错误消息。我在Constants + Macros.h文件中使用了2个宏。为了方便起见,我总是将此文件包含在前缀标头(MyApp-Prefix.pch)中。

常数+ Macros.h

1
2
3
4
// error handling ...

#define FS_ERROR_KEY(code)                    [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code)  NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)

3)现在很容易显示基于错误代码的用户友好错误消息。一个例子:

1
2
3
4
5
6
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
            message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
            delegate:nil
            cancelButtonTitle:@"OK"
            otherButtonTitles:nil];
[alert show];


很好的答案,Alex。一个潜在的问题是NULL取消引用。 Apple关于创建和返回NSError对象的参考

1
2
3
4
5
6
7
8
9
10
...
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];

if (error != NULL) {
    // populate the error object with the details
    *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
...

目标C

1
2
3
4
5
NSError *err = [NSError errorWithDomain:@"some_domain"
                                   code:100
                               userInfo:@{
                                           NSLocalizedDescriptionKey:@"Something went wrong"
                               }];

迅捷3

1
2
3
let error = NSError(domain:"some_domain",
                      code: 100,
                  userInfo: [NSLocalizedDescriptionKey:"Something went wrong"])


请参考以下教程

我希望它对您有帮助,但是在您必须阅读NSError文档之前

这是我最近发现的非常有趣的链接ErrorHandling


我见过的另一种设计模式涉及使用块,这在异步运行方法时特别有用。

假设我们定义了以下错误代码:

1
2
3
4
5
typedef NS_ENUM(NSInteger, MyErrorCodes) {
    MyErrorCodesEmptyString = 500,
    MyErrorCodesInvalidURL,
    MyErrorCodesUnableToReachHost,
};

您将定义可能引发如下错误的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
    if (path.length == 0) {
        if (failure) {
            failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
        }
        return;
    }

    NSString *htmlContents = @"";

    // Exercise for the reader: get the contents at that URL or raise another error.

    if (success) {
        success(htmlContents);
    }
}

然后,当您调用它时,您不必担心声明NSError对象(代码完成将为您完成)或检查返回值。您可以只提供两个块:一个在发生异常时将被调用,而另一个在成功时将被调用:

1
2
3
4
5
6
7
8
[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
    NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
    NSLog(@"Failed to get contents: %@", error);
    if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
        NSLog(@"You must provide a non-empty string");
    }
}];


我将尝试总结一下Alex和jlmendezbonini的观点的很好的答案,并添加一个修改内容,使所有ARC都兼容(到目前为止,这不是因为ARC会抱怨,因为您应该返回id,这意味着"任何对象",但是< x10>不是对象类型)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (BOOL) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        if (error != NULL) {
             // populate the error object with the details
             *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        }
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return NO;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
    return YES;
}

现在,我们检查error是否仍然是nil,而不是检查方法调用的返回值。如果不是,我们有问题。

1
2
3
4
5
6
7
8
9
// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.


好吧,这超出了问题范围,但是如果您没有NSError选项,则可以始终显示低级错误:

1
 NSLog(@"Error = %@",[NSString stringWithUTF8String:strerror(errno)]);