Question

I've developed some iOS 6.1 code to deal with NSError. But, I'm not happy with it. It is at best a hack:

 -(bool) reptErrAtModule: (NSString *) module
                  atSubr: (NSString *) subr
                  atFunc: (NSString *) func
                 withErr: (NSError *) err
   {
   id value = [[err userInfo] objectForKey: NSUnderlyingErrorKey];
   NSString * errDesc = (value != nil) ? 
                        [value localizedDescription]:
                        (NSString *)[[err userInfo] objectForKey: @"reason"];

   NSLog( @"ERR -> %@",[NSString stringWithFormat: 
          @"(%@>%@) %@ failed! %@",module,subr,func,errDesc] );
   }

I had a simpler form (without the (NSString *)[[err userInfo] objectForKey: @"reason"] case) and it worked for errors that I got back from calls to removeItemAtPath.

But then I got an error back from this code:

NSPersistentStore * entStor = 
 [myPerStoCor addPersistentStoreWithType: NSSQLiteStoreType
                           configuration: nil
                                     URL: [NSURL fileURLWithPath: Path]
                                 options: nil
                                   error: &err];

And my routine failed to extract the error. So I added the @"reason" logic because I could see the text I wanted in the Info data in the debugger.

Now the code works with both types of errors but I'm thinking this is not the way to do this. There must be a better, more generic way to deal with all the types of errors stuff the system can give you back in NSError.

Was it helpful?

Solution

I use this:

NSString *description = error.localizedDescription;
NSString *reason = error.localizedFailureReason;
NSString *errorMessage = [NSString stringWithFormat:@"%@ %@", description, reason];

OTHER TIPS

For debugging purposes, you ideally want to log out the entire contents of the error. Roughly speaking this is the domain, code, and userInfo. Bear in mind that userInfo might well include an underlying error, which you want to apply the same logic to. And in some cases, the error might supply a description (or failure reason etc.) which isn't present in the userInfo.

If you scroll down my blog post at http://www.mikeabdullah.net/easier-core-data-error-debugging.html, there's a snippet there showing how to generate a dictionary representation of an NSError object, and then get a string representation of that. This is pretty handy for debugging/logging purposes.

For presentation to users though, -[NSError localizedDescription] is expressly designed for such purposes. -localizedFailureReason serves a similar role, tending to specify what went wrong, without the context of the operation being tried. (One way to think of it is localizedDescription = task desceription + localizedFailureReason)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top