Capturing NSJSONSerialization errors in Swift

I am trying to understand why I cannot catch errors caused by NSJSONSerialization.

I expect the NSInvalidArgumentException be raised and caught, but the application will NSInvalidArgumentException instead.

This happens in both Swift 3 and Swift 2.3 using Xcode 8.

Swift 3:

  do { _ = try JSONSerialization.data(withJSONObject: ["bad input" : NSDate()]) } catch { print("this does not print") } 

Swift 2.3:

  do { _ = try NSJSONSerialization.dataWithJSONObject(["bad input" : NSDate()], options: NSJSONWritingOptions()) } catch { print("this does not print") } 

This code is placed in applicationDidFinishLaunching inside an empty Xcode project. Tested both on the simulator and on the device.

Full exception:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)' 

Any ideas why the catch block doesn't catch this particular error?

+6
source share
1 answer

From the documentation for JSONSerialization data(withJSONObject:options:) :

If obj does not produce valid JSON, an exception is thrown. This exception is thrown before parsing and is a programming error, not an internal error. You should check if the input will produce valid JSON before calling this method using isValidJSONObject (_ :).

This means that you cannot catch an exception caused by invalid data. Only "internal errors" (no matter what it really means) can be caught in a catch .

To avoid a possible NSInvalidArgumentException , you need to use isValidJSONObject .

Then your code will look like this:

 do { let obj = ["bad input" : NSDate()] if JSONSerialization.isValidJSONObject(obj) { _ = try JSONSerialization.data(withJSONObject: obj) } else { // not valid - do something appropriate } } catch { print("Some vague internal error: \(error)") } 
+9
source

Source: https://habr.com/ru/post/1012079/


All Articles