Pascal Bourque Pascal Bourque - 1 year ago 78
Swift Question

Occasional crash when accessing NSError.localizedDescription

In a Swift 1.2 app, I have some code that logs

objects. In very rare occasions, I get crash reports from Crashlytics indicating that accessing the
property caused the crash.

Here's my error logging function:

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

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
instead of via the
property, but since the callstack implies that it crashes while accessing a dictionary (which is most probably the
dict), I am afraid that it would not fix anything.

I don't mind not including the
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
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
property returns a valid string without crashing.

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

Answer Source

I ended up working around it by doing:

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

instead of accessing the property directly.