sk123
sk123

Reputation: 600

Crash when using error.localizedDescription from completion

I'm trying to check if error.localizedDescription contains a certain string but i keep getting a crash

if error.localizedDescription.contains("\"api.error.cardRejected.2000\"") {
   failCompletion()
 }

I have even tried to even use another way

if let description = (error! as NSError).userInfo[NSLocalizedDescriptionKey] as? String {
                if description.contains("api.error.cardRejected.2000") {
                     failCompletion()
                }
            }

I still keep getting the same crash in the logs saying

-[__NSDictionaryM domain]: unrecognized selector sent to instance 0x60000046b520

It works when i check using the debugDescription but i would like to check using the localizedDecription since the debug one only works when debugging

Upvotes: 1

Views: 966

Answers (1)

Asperi
Asperi

Reputation: 257711

NSError localized description is autogenerated from what's inside, here is what API tells:

/* The primary user-presentable message for the error, for instance for NSFileReadNoPermissionError: "The file "File Name" couldn't be opened because you don't have permission to view it.". This message should ideally indicate what failed and why it failed. This value either comes from NSLocalizedDescriptionKey, or NSLocalizedFailureErrorKey+NSLocalizedFailureReasonErrorKey, or NSLocalizedFailureErrorKey. The steps this takes to construct the description include:
 1. Look for NSLocalizedDescriptionKey in userInfo, use value as-is if present.
 2. Look for NSLocalizedFailureErrorKey in userInfo. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.
 3. Fetch NSLocalizedDescriptionKey from userInfoValueProvider, use value as-is if present.
 4. Fetch NSLocalizedFailureErrorKey from userInfoValueProvider. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.
 5. Look for NSLocalizedFailureReasonErrorKey in userInfo or from userInfoValueProvider; combine with generic "Operation failed" message.
 6. Last resort localized but barely-presentable string manufactured from domain and code. The result is never nil.
*/
open var localizedDescription: String { get }

so, it is crashed (probably at step 6.) then this NSError is incorrectly constructed - so find who & how constructed it, possibly at some layer on underlying errors some key of userInfo unexpectedly is set as NSDictionary instead of NSError.

Upvotes: 1

Related Questions