Pascal Bourque Pascal Bourque - 4 months ago 20
Swift Question

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?

Answer

I ended up working around it by doing:

if let localizedDescription = error.userInfo[NSLocalizedDescriptionKey] as? String {}

instead of accessing the property directly.

Comments