Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Occasional crash when accessing NSError.localizedDescription

In a Swift 1.2 app, I have some code that logs NSError objects. In very rare occasions, I get crash reports from Crashlytics indicating that accessing the localizedDescription property caused the crash.

Here's my error logging function:

func trackError(error: NSError)
{
    var props = [String: AnyObject]()

    // CRASHES HERE
    props["NSErrorLocalized"] = error.localizedDescription

    props["NSErrorCode"] = error.code
    props["NSErrorDomain"] = error.domain

    if let userInfo = error.userInfo {
        props["NSErrorUserInfo"] = userInfo
    }

    self.trackEvent("Error", withProperties: props)
}

And here's the call stack reported by Crashlytics:

0 CoreFoundation  CFHash + 129
1 CoreFoundation  CFBasicHashFindBucket + 1204
2 CoreFoundation  CFBasicHashFindBucket + 1204
3 CoreFoundation  CFDictionaryGetValue + 106
4 CoreFoundation  _CFErrorCreateLocalizedDescription + 266
5 Foundation      -[NSError localizedDescription] + 82

I was thinking on directly accessing the NSLocalizedDescriptionKey in error.userInfo instead of via the localizedDescription property, but since the callstack implies that it crashes while accessing a dictionary (which is most probably the userInfo dict), I am afraid that it would not fix anything.

I don't mind not including the localizedDescription in my error log if there is none, but I need a safe way to check if there is one or not without crashing...

Something that might be noteworthy: it seems like the NSError objects that cause this crash are ones that are returned by the Parse SDK. I have no way to be sure of this, but there are some clues in the rest of my logs that seem to imply this.

I have tried to reproduce this by forcing error situations with various calls to the Parse SDK, but my error logging code handle them without any problems and the localizedDescription property returns a valid string without crashing.

Anybody else has seen this and has any clue on what is going on?

like image 721
Pascal Bourque Avatar asked Feb 10 '23 12:02

Pascal Bourque


1 Answers

One possible way this could crash is if errors are created (in Objective-C) like [NSError new] or [[NSError alloc] init] (i.e., not calling the designated initializer). At least in iOS9, that returns a valid instance, but its internals are not properly initialized and can crash if you call methods on it. Calling -userInfo just returns an empty dictionary, but trying to access other internal state like -localizedDescription and similar methods can do will cause crashes.

like image 113
Carl Lindberg Avatar answered Feb 22 '23 22:02

Carl Lindberg