【发布时间】:2015-11-05 19:14:32
【问题描述】:
我正在使用NSFileManager.contentsOfDirectoryAtPath 来获取目录中的文件名数组。我想使用新的do-try-catch 语法来处理错误:
do {
let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch {
// handle errors
print(error) // this is the best I can currently do
}
我可以想象一个错误可能是docsPath 不存在,但我不知道如何捕捉这个错误。而且我不知道可能会发生什么其他错误。
文档示例
Error Handling documentation 有一个这样的例子
enum VendingMachineError: ErrorType {
case InvalidSelection
case InsufficientFunds(centsNeeded: Int)
case OutOfStock
}
和
do {
try vend(itemNamed: "Candy Bar")
// Enjoy delicious snack
} catch VendingMachineError.InvalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let amountNeeded) {
print("Insufficient funds. Please insert an additional \(amountNeeded) cents.")
}
但我不知道如何做类似的事情来捕获具有使用 throws 关键字的方法的标准 Swift 类型的错误。
NSFileManager class reference for contentsOfDirectoryAtPath 没有说明可能会返回什么样的错误。所以我不知道要捕获什么错误,或者如果我得到它们如何处理它们。
更新
我想做这样的事情:
do {
let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch FileManagerError.PathNotFound {
print("The path you selected does not exist.")
} catch FileManagerError.PermissionDenied {
print("You do not have permission to access this directory.")
} catch ErrorType {
print("An error occured.")
}
【问题讨论】:
-
@JAL,是的,这个问题很相似。在您的回答中,您展示了如何获取
NSError,但您没有提供有关如何区分和处理不同类型错误的任何详细信息。 -
也相关(参见 cmets 中的讨论):Find what errors a function can throw in Xcode with Swift 确实无法获得函数抛出的
ErrorTypes 列表。ErrorType是一个枚举对象可以遵循的协议(NSError遵循ErrorType,具体错误需要查看返回的错误码)。
标签: ios macos swift error-handling