我正在努力捕捉我的应用程序中的错误,我正在寻找使用NSError。对于如何使用它,以及如何填充它,我有点困惑。

有人能提供一个例子,我如何填充然后使用NSError?


当前回答

我看到的另一种设计模式涉及到使用块,这在方法异步运行时尤其有用。

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

typedef NS_ENUM(NSInteger, MyErrorCodes) {
    MyErrorCodesEmptyString = 500,
    MyErrorCodesInvalidURL,
    MyErrorCodesUnableToReachHost,
};

你可以这样定义你的方法来引发一个错误:

- (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对象(代码补全将为你完成),或检查返回值。你可以只提供两个块:一个在有异常时被调用,另一个在成功时被调用:

[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");
    }
}];

其他回答

好吧,我通常做的是让我的方法在运行时可以error-out引用一个NSError指针。如果在该方法中确实出现了错误,我可以用错误数据填充NSError引用,并从该方法返回nil。

例子:

- (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,否则不要检查错误对象:

// 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设置了一个值。

了解更多信息的最好地方是苹果的文档。它真的很好。

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

这有点超出了问题范围,但如果你没有NSError选项,你可以总是显示低级别错误:

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

答得好,亚历克斯。一个潜在的问题是NULL解引用。Apple关于创建和返回NSError对象的参考

...
[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;
...

objective - c

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

斯威夫特3

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

我看到的另一种设计模式涉及到使用块,这在方法异步运行时尤其有用。

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

typedef NS_ENUM(NSInteger, MyErrorCodes) {
    MyErrorCodesEmptyString = 500,
    MyErrorCodesInvalidURL,
    MyErrorCodesUnableToReachHost,
};

你可以这样定义你的方法来引发一个错误:

- (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对象(代码补全将为你完成),或检查返回值。你可以只提供两个块:一个在有异常时被调用,另一个在成功时被调用:

[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");
    }
}];