如何在 iOS 中获取 NSError 消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3446867/
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
How to get the NSError message in iOS?
提问by Monish Kumar
I am having the method in my view controller as shown below:
我的视图控制器中有该方法,如下所示:
- (void)parser:(PaymentTermsLibxmlParser *)parser encounteredError:(NSError *)error
{
NSLog("error occured");
}
Here I need to show the Actual error message in the NSError in my alert can any one suggest how to get it.
在这里,我需要在我的警报中的 NSError 中显示实际错误消息,任何人都可以建议如何获取它。
回答by jtbandes
Normally you'll want to use [error localizedDescription]
to get the text to show to the user.
通常,您需要使用[error localizedDescription]
来获取要显示给用户的文本。
Read the NSError documentation for more options.
阅读 NSError 文档以获取更多选项。
For simple logging when developing, you can do NSLog(@"Error: %@", error)
. (That will give you 'localizedDescription' and everything else on your log in Xcode.)
对于开发时的简单日志记录,您可以执行NSLog(@"Error: %@", error)
. (这将为您提供 'localizedDescription' 以及您登录 Xcode 的所有其他内容。)
回答by mkodamati
use [error localizedDescription]
which displays the error Message
使用[error localizedDescription]
它显示错误消息
回答by Alex Zavatone
To add to the current answers, you can get the failure message and the failure reason. To do that, you can do this when presented with an NSError:
要添加到当前答案,您可以获得失败消息和失败原因。为此,您可以在出现 NSError 时执行此操作:
NSString *message = [NSString stringWithFormat:@"%s\n%@\n%@", __PRETTY_FUNCTION__, displayRegion, [error localizedDescription], [error localizedFailureReason]];
This will create a 3 line string with the name of the method where the error occurred, the description of the error and a sentence explaining the error.
这将创建一个 3 行的字符串,其中包含发生错误的方法的名称、错误的描述和解释错误的句子。
If more info is be supplied in the NSError, you can get the localizedRecoverySuggestion as well and add that to the message like so:
如果在 NSError 中提供了更多信息,您也可以获取 localizedRecoverySuggestion 并将其添加到消息中,如下所示:
NSString *message = [NSString stringWithFormat:@"%s\n%@\n%@\n%@", __PRETTY_FUNCTION__, displayRegion, [error localizedDescription], [error localizedFailureReason], [error localizedRecoverySuggestion]];
回答by Baljeet Singh
User error.userInfo, it returns dictionary ex:
用户 error.userInfo,它返回字典 ex:
NSLog(@"%@",error.userInfo);
{
code = 101;
error = "invalid login parameters";
originalError = "Error Domain=NSURLErrorDomain Code=-1011 \"The operation couldn\U2019t be completed. (NSURLErrorDomain error -1011.)\"";
temporary = 0;
}