ios 如何从 NSError 获取更多有用的信息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11028902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:46:14  来源:igfitidea点击:

How can I get more useful information from NSError?

iosnserror

提问by kevin young

I want to get some useful information from NSError. If I print out [error userInfo], I get the following:

我想从NSError. 如果我打印出来[error userInfo],我会得到以下信息:

{
    NSFilePath = "/Users/apple/Library/Application Support/iPhone Simulator/5.1/Applications/08260B6A-4D65-48DF-ADD1-FFC8750081E8/Documents/abc";
    NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=17 \"The operation couldn\U2019t be completed. File exists\"";
}

I want to show the last line : "File exists", but how can i pick it out?

我想显示最后一行:“文件存在”,但我怎样才能把它挑出来?

I tried:

我试过:

localizedDescription
localizedFailureReason
localizedRecoverySuggestion
localizedRecoveryOptions
recoveryAttempter

Non of them show "File exists".

他们都没有显示“文件存在”。

回答by kevin young

Finally, I follow code for perfect NSError print. Thanks @jbat100 and @Peter Warbo, I add a little bit on them code:

最后,我按照代码进行完美的 NSError 打印。感谢@jbat100 和@Peter Warbo,我在他们上面加了一点代码:

    NSDictionary *userInfo = [error userInfo];
    NSString *errorString = [[userInfo objectForKey:NSUnderlyingErrorKey] localizedDescription];

回答by Peter Warbo

How about:

怎么样:

NSDictionary *userInfo = [error userInfo];
NSString *error = [userInfo objectForKey:@"NSUnderlyingError"];
NSLog(@"The error is: %@", error);

回答by jbat100

If you look up the NSError documentation, it has a User info dictionary keyssection which has a constant defined as NSUnderlyingErrorKey (it also has a description for the keys).

如果您查找NSError 文档,它有一个User info dictionary keys部分,其中有一个定义为 NSUnderlyingErrorKey 的常量(它还具有键的描述)。

NSDictionary *userInfo = [error userInfo];
NSError *underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey];
NSString *underlyingErrorDescription = [underlyingError localizedDescription];

回答by lansher1985

localizedRecoverySuggestion is very useful. You can get the JSON string from it:

localizedRecoverySuggestion 非常有用。您可以从中获取 JSON 字符串:

NSString *JSON = [[error userInfo] valueForKey:NSLocalizedRecoverySuggestionErrorKey] ;

            NSError *aerror = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding]
                                                                 options: NSJSONReadingMutableContainers
                                                                   error: &aerror];