在 Swift 中捕获 NSJSONSerialization 错误
Catching NSJSONSerialization errors in Swift
我想了解为什么我无法捕获 NSJSONSerialization 抛出的错误。
我希望引发并捕获 NSInvalidArgumentException
异常,但应用程序崩溃了。
这发生在 Swift 3 和 Swift 2.3 中使用 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")
}
此代码放在空白 Xcode 项目中的 applicationDidFinishLaunching
中。在模拟器和设备上测试。
完全异常:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
知道为什么 catch 块没有捕捉到这个特定错误吗?
来自 JSONSerialization data(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(_:).
这意味着你无法捕获由无效数据引起的异常。只有 "internal errors"(无论实际意味着什么)可以在 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)")
}
我想了解为什么我无法捕获 NSJSONSerialization 抛出的错误。
我希望引发并捕获 NSInvalidArgumentException
异常,但应用程序崩溃了。
这发生在 Swift 3 和 Swift 2.3 中使用 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")
}
此代码放在空白 Xcode 项目中的 applicationDidFinishLaunching
中。在模拟器和设备上测试。
完全异常:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
知道为什么 catch 块没有捕捉到这个特定错误吗?
来自 JSONSerialization data(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(_:).
这意味着你无法捕获由无效数据引起的异常。只有 "internal errors"(无论实际意味着什么)可以在 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)")
}