ios – 如何找到一种方法可能会抛出的错误并捕获它们在Swift

参见英文答案 > How get the list of errors thrown by a function?2
我正在使用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.")
}

解决方法

NSError自动桥接到域类型的错误类型(例如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)
}

至于知道特定呼叫可以返回哪个错误,只有文档可以帮助.几乎所有的基础错误都是NSCocoaError域的一部分,可以在FoundationErrors.h中找到(尽管有一些罕见的错误,基金会有时也会在NSPOSIXErrorDomain下返回POSIX错误),但是这些错误可能还没有被完全桥接,所以你必须回到在NSError级别管理它们.

更多信息,请参见«Using Swift with Cocoa and Objective-C (Swift 2.2)»

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...