问题描述
文档和流行博客建议使用do-catch完成Swift错误处理并处理ErrorType枚举或NSError实例。
The docs and popular blogs suggest Swift error handling be done with do-catch and to handle an ErrorType enum or an NSError instance.
ErrorType枚举和NSError实例是在尝试捕获块中互斥?如果没有,那么如何实现同时抛出两者的函数呢?
Are ErrorType enum and NSError instances mutually exclusive in a try catch block? If not, how do you implement a function that throws both?
我已经将NSError实例与这样的枚举相关联,这似乎可以正常工作,但这是否是de返回详细的错误信息的事实方法?
I have associated an NSError instance to an enum like so, which seems to work, but is this the de facto way of returning detailed error information?
enum Length : ErrorType {
case NotLongEnough(NSError)
case TooLong(NSError)
}
func myFunction() throws {
throw Length.NotLongEnough(NSError(domain: "domain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "Not long enough mate"]))
}
do {
try myFunction()
} catch Length.NotLongEnough(let error) {
print("\(error)")
}
此示例显示ErrorType如何
This example shows how ErrorType can be cast to NSError.
do {
let str = try NSString(contentsOfFile: "Foo.bar",
encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
print(error.localizedDescription)
}
我找不到符合NSString的ErrorType的错误枚举,所以我们应该假设它是NSError实例?当然可以确保可以运行代码,但是文档一定会让我们知道。 (不胜感激,我可能会误读文档)
I can't find an error enum that conforms to ErrorType for NSString so should we assume it will be an NSError instance ? Granted we could run the code to be sure, but surely the docs should let us know. (I appreciate I might have mis-read the docs)
推荐答案
NSError
类采用 ErrorType
接口,任何与 ErrorType
兼容的类都可以强制转换为 NSError
。在。
NSError
class adopts ErrorType
interface and any ErrorType
-conformant class can be casted to NSError
. These features are described here in the docs.
您可以放心地坚持 ErrorType
enum CommonError: ErrorType {
case InternalInconsistency(String)
}
func boom() throws {
throw CommonError.InternalInconsistency("Boom!")
}
do {
try boom()
} catch {
print(error) // InternalInconsistency("Boom!")
print(error as NSError) // Error Domain=CommonError Code=0 "(null)"
}
do {
try boom()
} catch let CommonError.InternalInconsistency(msg) {
print("Error: \(msg)") // Error: Boom!
}
这篇关于Swift:现在应该将NSError视为旧版吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!