Best Practice - NSError domains and codes for your own project/app

Viewed 34324

There is a previous SO post regarding setting up error domains for your own frameworks, but what is the best practice regarding setting up error domains and custom error codes for your own project/app?

For example, supposing you're working on a Core Data-intensive app with lots of validations, should you just stick with the "off the shelf" Core Data error codes (such as NSManagedObjectValidationError from CoreDataErrors.h) or should you create your own MyAppErrors.h and define errors with more specificity (i.e., MyAppValidationErrorInvalidCombinationOfLimbs?

Creating a custom error domain and set of error codes could significantly disambiguate your code, but is it too much overhead to maintain and does one have to worry about error code numbering conflicts? Or are there other concerns here?

3 Answers

How to create a custom NSError:

First create a Dictionary of the error message

NSDictionary *userInfo = @{   
   NSLocalizedDescriptionKey: NSLocalizedString(@"Unknown Error - Please try again", nil),
   NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Unknown Error - Please try again", nil),
   NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Unknown Error - Please try again", nil)
                                               };
NSError *error = [NSError errorWithDomain:[[NSBundle mainBundle] bundleIdentifier] 
  code:-58 userInfo:userInfo];

Then assign the userInfo to the NSDictionary and your done.

Related