需要一种通用的方法来提取错误文本

时间:2013-09-05 11:49:56

标签: ios nserror

我已经开发了一些iOS 6.1代码来处理NSError。但是,我对它并不满意。它充其量只是一个黑客:

 -(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] );
   }

我有一个更简单的表单(没有(NSString *)[[err userInfo] objectForKey: @"reason"]情况),它适用于我从调用removeItemAtPath回来的错误。

但后来我从这段代码中得到了一个错误:

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

我的例程未能提取错误。所以我添加了@"reason"逻辑,因为我可以在调试器的Info数据中看到我想要的文本。

现在代码适用于两种类型的错误,但我认为这不是这样做的方法。必须有一种更好,更通用的方法来处理系统可以在NSError中返回的所有类型的错误。

2 个答案:

答案 0 :(得分:0)

我用这个:

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

答案 1 :(得分:0)

出于调试目的,理想情况下要注销错误的全部内容。粗略地说,这是domaincodeuserInfo。请记住,userInfo可能包含基础错误,您希望将相同的逻辑应用于该错误。在某些情况下,错误可能会提供isn't present in the userInfo

的描述(或失败原因等)

如果您在http://www.mikeabdullah.net/easier-core-data-error-debugging.html向下滚动我的博文,那里有一个片段,展示如何生成NSError对象的字典表示,然后获取该字符串表示。这对于调试/记录来说非常方便。

虽然为了向用户展示,-[NSError localizedDescription]是专为此目的而设计的。 -localizedFailureReason扮演类似的角色,倾向于指定出错的地方,而没有尝试操作的上下文。 (想到它的一种方法是localizedDescription = task desceription + localizedFailureReason