Breaking News
Home / iOS / iOS Tutorials / Using NSError Explained

Using NSError Explained

What is NSErrorOne of common ways for Error handling and error code propagation is the use of try/catch blocks to catch an exception and throw clause to throw an exception. Traditional programmers would prefer just to return an error code and description and not use these try/catch way of exception propagation. NSError object is certainly the way to go for developers.<!

NSError

The NSError object has the following members

Members

NSInteger _code;
    NSString *_domain;
    NSDictionary *_userInfo;

Contstructors
/* Designated initializer. Domain cannot be nil; dict may be nil if no userInfo desired.
*/
– (id)initWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict;
+ (id)errorWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict;

/* These define the error. Domains are described by names that are arbitrary strings used to differentiate groups of codes; for custom domain using reverse-DNS naming will help avoid conflicts. Codes are domain-specific.
*/
– (NSString *)domain;
– (NSInteger)code;

/* Additional info which may be used to describe the error further. Examples of keys that might be included in here are “Line Number”, “Failed URL”, etc. Embedding other errors in here can also be used as a way to communicate underlying reasons for failures; for instance “File System Error” embedded in the userInfo of an NSError returned from a higher level document object. If the embedded error information is itself NSError, the standard key NSUnderlyingErrorKey can be used.
*/
– (NSDictionary *)userInfo;

/* The primary user-presentable message for the error. This method can be overridden by subclassers wishing to present better error strings.  By default this looks for NSLocalizedDescriptionKey in the user info. If not present, it manufactures a string from the domain and code. Also, for some of the built-in domains it knows about, it might try to fetch an error string by calling a domain-specific function. In the absence of a custom error string, the manufactured one might not be suitable for presentation to the user, but can be used in logs or debugging.
*/
– (NSString *)localizedDescription;

 

Example

In the below example we use pass the address of NSError object to the executeMethod. If there is an error in the method execution it would be populated with an errorCode/error

NSError* error = nil;
  [self executeMethod withError:&error];

    if (error)
    {

        NSLog(@”Error Descr %@”,error.localizedDescription);

        NSLog(@”Error Code %@”,error.code);    

        NSLog(@”Error Domain %@”,error.domain);   

}

else

{

  NSLog(@”No error, all is well”);

}[pb_builder]

Advertisment ad adsense adlogger