我试图理解为什么我无法捕捉到NS
JSONSerialization引发的错误.
我希望引发和捕获NSInvalidArgumentException异常,但应用程序崩溃.
使用Xcode 8在Swift 3和Swift 2.3中都会发生这种情况.
斯威夫特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") }
此代码放在applicationDidFinishLaunching一个空白的Xcode项目中.在模拟器和设备上进行测试.
完全例外:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: 'Invalid type in JSON write (__NSDate)'
任何想法为什么catch块没有捕获这个特定的错误?
解决方法
从JSONSerialization数据的文档(withJSONObject:options :):
If obj will not produce valid JSON,an exception is thrown. This exception is thrown prior to parsing and represents a programming error,not an internal error. You should check whether the input will produce valid JSON before calling this method by using isValidJSONObject(_:).
这意味着您无法捕获由无效数据导致的异常.只有“内部错误”(无论实际意味着什么)才能在catch块中捕获.
要避免可能的NSInvalidArgumentException,您需要使用isValidJSONObject.
然后你的代码变成:
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)") }