如何找到方法可能抛出的错误并在Swift中捕获它们

Sur*_*gch 16 macos error-handling ios swift

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

}
Run Code Online (Sandbox Code Playgroud)

我可以想象一个错误可能是docsPath不存在的错误,但我不知道如何捕获这个错误.我不知道可能发生的其他错误.

文档示例

错误处理的文件有这样一个例子

enum VendingMachineError: ErrorType {
    case InvalidSelection
    case InsufficientFunds(centsNeeded: Int)
    case OutOfStock
}
Run Code Online (Sandbox Code Playgroud)

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.")
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何做类似的事情来捕捉使用throws关键字的方法的标准Swift类型的错误.

对的NSFileManager类的引用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.")
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ien 13

NSError自动桥接到ErrorType域成为类型的位置(例如NSCocoaErrorDomain变为NSCocoaError),错误代码变为值(NSFileReadNoSuchFileError变为.FileReadNoSuchFileError)

import Foundation

let docsPath = "/file/not/found"
let fileManager = NSFileManager()

do {
    let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch NSCocoaError.FileReadNoSuchFileError {
    print("No such file")
} catch {
    // other errors
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

至于知道特定调用可以返回哪个错误,只有文档可以提供帮助.几乎所有的Foundation错误都是NSCocoaError域的一部分,并且可以找到FoundationErrors.h(尽管有一些罕见的错误,基金会有时也可以返回POSIX错误NSPOSIXErrorDomain),但这些错误可能没有完全桥接,因此您将不得不依赖于管理它们在这个NSError级别.

更多信息可以在«使用Swift with Cocoa和Objective-C(Swift 2.2)中找到»