一蓬豁、NSError是系統(tǒng)錯誤信息類
//兩種初始化方法:其中见坑,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開發(fā)蕾总,一般使用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, @"恢復建議:請創(chuàng)建該文件",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
系統(tǒng)的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;">
//
// YXError.h
// CustomYXError
//
// Copyright (c) 2014年 Y.X. All rights reserved.
//
-
import <Foundation/Foundation.h>
// 自行添加錯誤碼
typedef enum : NSUInteger {
Crash = -10000,
DisConnect,
Unknow,
} YXErrorCode;
@interface YXError : NSObject
- (NSError *)errorCode:(YXErrorCode)code userInfo:(NSDictionary *)dic;
- (NSString *)transformCodeToStringInfo:(YXErrorCode)code;
@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;">
//
// YXError.m
// CustomYXError
//
// Copyright (c) 2014年 Y.X. All rights reserved.
//
-
import "YXError.h"
static NSDictionary *errorDictionary = nil;
@implementation YXError
- (void)initialize
{
if (self == [YXError class])
{
errorDictionary = \
@{
/* code : errorWithDomain */
/* ==================================== */
@(Crash) : @"Crash",
@(DisConnect) : @"DisConnect",
@(Unknow) : @"Unknow",
/* ==================================== */
};
}
}
- (NSError *)errorCode:(YXErrorCode)code userInfo:(NSDictionary *)dic
{
return [NSError errorWithDomain:errorDictionary[@(code)]
code:code
userInfo:dic];
}
- (NSString *)transformCodeToStringInfo:(YXErrorCode)code
{
return errorDictionary[@(code)];
}
@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;">
-
import "AppDelegate.h"
-
import "YXError.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 定制一個NSError
NSError *error = [YXError errorCode:Crash
userInfo:nil];
NSLog(@"%@", error);
// 翻譯一個NSError(將code值翻譯成字符串)
NSLog(@"%@", [YXError transformCodeToStringInfo:-10000]);
return YES;
}
@end
參考鏈接:https://blog.csdn.net/hdfqq188816190/article/details/52754943