自定义NSError代码

时间:2015-04-29 10:13:13

标签: ios objective-c nserror

我正在构建一个Cocoa Touch Framework,它使用自定义的NSError对象将错误传回给调用者。我需要声明一个定义自定义错误代码的枚举。我转到此Apple doc,其中列出了NSURLErrorDomain错误代码,如下所示:

enum {    
   NSURLErrorUnknown = -1,   
   NSURLErrorCancelled = -999,   
   NSURLErrorBadURL = -1000,    
   NSURLErrorTimedOut = -1001,   
   NSURLErrorUnsupportedURL = -1002,
   NSURLErrorUnsupportedURL = -1002,
   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,   
   NSURLErrorInternationalRoamingOff = -1018,    
   NSURLErrorCallIsActive = -1019,    
   NSURLErrorDataNotAllowed = -1020,    
   NSURLErrorRequestBodyStreamExhausted = -1021,   
   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 
   }

Q1: 为什么Apple使用负值来表示错误代码?这有什么具体原因吗?

Q2: Apple是否遵循随机化错误代码的任何模式?

1 个答案:

答案 0 :(得分:4)

  1. 因为基于返回码,0通常可以。这留下正面和负面整数。它的一般C偏好是使用正整数表示成功代码(附加信息)和负值表示错误代码。
  2. 如您所见,错误代码已分组。未知和取消是特殊的,1000是HTTP错误,1100是访问错误,1200是连接和证书错误,2000网络,3000s文件和流问题。
  3. 根据问题区域对错误进行分组,并将负数用于返回代码目的(因为返回负数通常会被解释为错误)。