iOS NSError详解 NSError错误code对照表 自定义、定制NSError 一看就懂

一、NSError是系统错误信息类

//两种初始化方法:其中,domain 不能为空 dict可以为空

  • (instancetype)initWithDomain:(NSErrorDomain)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict;
  • (instancetype)errorWithDomain:(NSErrorDomain)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict;

@property (readonly, copy) NSErrorDomain domain;//错误域

错误域主要有四个,对于Carbon框架的Error,归于OSStatus domain(NSOSStatusErrorDomain),对于POSIX error,归于NSPOSIXErrorDomain,而对于我们的iOS开发,一般使用NSCocoaErrorDomain。NSError.h定义了四个domain

{

// Predefined domain for errors from most AppKit and Foundation APIs.
FOUNDATION_EXPORT NSErrorDomain const NSCocoaErrorDomain;

// Other predefined domains; value of "code" will correspond to preexisting values in these domains.
FOUNDATION_EXPORT NSErrorDomain const NSPOSIXErrorDomain;
FOUNDATION_EXPORT NSErrorDomain const NSOSStatusErrorDomain;
FOUNDATION_EXPORT NSErrorDomain const NSMachErrorDomain;

}

@property (readonly) NSInteger code;//错误代码

@property (readonly, copy) NSDictionary *userInfo;//错误信息

@property (readonly, copy) NSString *localizedDescription;//获取本地化描述

@property (nullable, readonly, copy) NSString *localizedFailureReason;//获取失败原因

@property (nullable, readonly, copy) NSString *localizedRecoverySuggestion;//获取恢复建议

@property (nullable, readonly, copy) NSArray<NSString *> *localizedRecoveryOptions;本地恢复建议

@property (nullable, readonly, strong) id recoveryAttempter;

@property (nullable, readonly, copy) NSString *helpAnchor;

预定义的userinfo键名

NSString *const NSUnderlyingErrorKey;//推荐的标准方式,通用键
NSString *const NSLocalizedDescriptionKey; // 详细描述键
NSString *const NSLocalizedFailureReasonErrorKey; // 失败原因键
NSString *const NSLocalizedRecoverySuggestionErrorKey; //恢复建议键
NSString *const NSLocalizedRecoveryOptionsErrorKey; // 恢复选项键

//其他键

NSString *const NSRecoveryAttempterErrorKey;
NSString *const NSHelpAnchorErrorKey;
NSString *const NSStringEncodingErrorKey ;
NSString *const NSURLErrorKey;
NSString *const NSFilePathErrorKey;

用法示例:

NSDictionary *userInfo1 = [NSDictionary dictionaryWithObjectsAndKeys:@"由于文件不存在,无法打开", NSLocalizedDescriptionKey, @"失败原因:文件不存在", NSLocalizedFailureReasonErrorKey, @"恢复建议:请创建该文件",NSLocalizedRecoverySuggestionErrorKey,nil];

NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:userInfo1];//此处code是4,对照下面对照表4代表文件不存在。userinfo传userinfo1 查看自定义打印。userinfo传nil,查看本地化描述。

NSLog(@"========%@",[error localizedDescription]);
NSLog(@"========%@",[error localizedFailureReason]);
NSLog(@"========%@",[error localizedRecoverySuggestion]);

二、NSError错误code对照表

Foundation Constants Reference
NSError Codes

NSError codes in the Cocoa error domain.

enum {
NSFileNoSuchFileError = 4,
NSFileLockingError = 255,
NSFileReadUnknownError = 256,
NSFileReadNoPermissionError = 257,
NSFileReadInvalidFileNameError = 258,
NSFileReadCorruptFileError = 259,
NSFileReadNoSuchFileError = 260,
NSFileReadInapplicableStringEncodingError = 261,
NSFileReadUnsupportedSchemeError = 262,
NSFileReadTooLargeError = 263,
NSFileReadUnknownStringEncodingError = 264,
NSFileWriteUnknownError = 512,
NSFileWriteNoPermissionError = 513,
NSFileWriteInvalidFileNameError = 514,
NSFileWriteInapplicableStringEncodingError = 517,
NSFileWriteUnsupportedSchemeError = 518,
NSFileWriteOutOfSpaceError = 640,
NSFileWriteVolumeReadOnlyError = 642m
NSKeyValueValidationError = 1024,
NSFormattingError = 2048,
NSUserCancelledError = 3072,

NSFileErrorMinimum = 0,
NSFileErrorMaximum = 1023,
NSValidationErrorMinimum = 1024,
NSValidationErrorMaximum = 2047,
NSFormattingErrorMinimum = 2048,
NSFormattingErrorMaximum = 2559,

NSPropertyListReadCorruptError = 3840,
NSPropertyListReadUnknownVersionError = 3841,
NSPropertyListReadStreamError = 3842,
NSPropertyListWriteStreamError = 3851,
NSPropertyListErrorMinimum = 3840,
NSPropertyListErrorMaximum = 4095

NSExecutableErrorMinimum = 3584,
NSExecutableNotLoadableError = 3584,
NSExecutableArchitectureMismatchError = 3585,
NSExecutableRuntimeMismatchError = 3586,
NSExecutableLoadError = 3587,
NSExecutableLinkError = 3588,
NSExecutableErrorMaximum = 3839,

}
URL Loading System Error Codes

These values are returned as the error code property of an NSError object with the domain “NSURLErrorDomain”.

typedef enum
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorDataLengthExceedsMaximum = -1103,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete = -3007
}

三、自定义NSError

系统的NSError是可以自己定制的,以下提供代码来实现并表示如何使用:

YXError.h 与 YXError.m

[objc] view plaincopy

<embed id="ZeroClipboardMovie_1" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_1" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=1&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

<embed id="ZeroClipboardMovie_4" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_4" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=4&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

  1. //

  2. // YXError.h

  3. // CustomYXError

  4. //

  5. // Copyright (c) 2014年 Y.X. All rights reserved.

  6. //

  7. import <Foundation/Foundation.h>

  8. // 自行添加错误码

  9. typedef enum : NSUInteger {

  10. Crash = -10000,

  11. DisConnect,

  12. Unknow,

  13. } YXErrorCode;

  14. @interface YXError : NSObject

    • (NSError *)errorCode:(YXErrorCode)code userInfo:(NSDictionary *)dic;
    • (NSString *)transformCodeToStringInfo:(YXErrorCode)code;
  15. @end

[objc] view plaincopy

<embed id="ZeroClipboardMovie_2" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_2" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=2&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

<embed id="ZeroClipboardMovie_5" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_5" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=5&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

  1. //

  2. // YXError.m

  3. // CustomYXError

  4. //

  5. // Copyright (c) 2014年 Y.X. All rights reserved.

  6. //

  7. import "YXError.h"

  8. static NSDictionary *errorDictionary = nil;

  9. @implementation YXError

    • (void)initialize
  10. {

  11. if (self == [YXError class])

  12. {

  13. errorDictionary = \

  14. @{

  15. /* code : errorWithDomain */

  16. /* ==================================== */

  17. @(Crash) : @"Crash",

  18. @(DisConnect) : @"DisConnect",

  19. @(Unknow) : @"Unknow",

  20. /* ==================================== */

  21. };

  22. }

  23. }

    • (NSError *)errorCode:(YXErrorCode)code userInfo:(NSDictionary *)dic
  24. {

  25. return [NSError errorWithDomain:errorDictionary[@(code)]

  26. code:code

  27. userInfo:dic];

  28. }

    • (NSString *)transformCodeToStringInfo:(YXErrorCode)code
  29. {

  30. return errorDictionary[@(code)];

  31. }

  32. @end

以下是使用的代码:

[objc] view plaincopy

<embed id="ZeroClipboardMovie_3" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_3" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=3&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

<embed id="ZeroClipboardMovie_6" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_6" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=6&width=16&height=16" wmode="transparent" style="box-sizing: border-box; outline: 0px; word-break: break-all;">

  1. import "AppDelegate.h"

  2. import "YXError.h"

  3. @implementation AppDelegate

    • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  4. {

  5. // 定制一个NSError

  6. NSError *error = [YXError errorCode:Crash

  7. userInfo:nil];

  8. NSLog(@"%@", error);

  9. // 翻译一个NSError(将code值翻译成字符串)

  10. NSLog(@"%@", [YXError transformCodeToStringInfo:-10000]);

  11. return YES;

  12. }

  13. @end

参考链接:https://blog.csdn.net/hdfqq188816190/article/details/52754943

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容