One of the common ways of error handling and error code propagation is the use of try/catch blocks to catch an exception and throw clause to throw an exception. So programmers would prefer just to return an error code and description and not use these try/catch way of exception propagation. For such programmers, NSError provides a placeholder to store information related to the error and return it back to the caller.

NSError

The NSError object has the following members:

Members

NSInteger _code;
NSString *_domain;
NSDictionary *_userInfo;
Constructors
/* Designated initializer. The 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 pass the address of the NSError object to the executeMethod. If there is an error in the method execution, it would be populated with the error details:

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”);
}