I am using NSFileManager.contentsOfDirectoryAtPath
to get an array of file names in a directory. I want to use the new do-try-catch
syntax to handle the errors:
do {
let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch {
// handle errors
print(error) // this is the best I can currently do
}
I can imaging that an error might be that the docsPath
doesn't exist, but I don't know how to catch this error. And I don't know what other possible errors might occur.
Documentation example
The Error Handling documentation has an example like this
enum VendingMachineError: ErrorType {
case InvalidSelection
case InsufficientFunds(centsNeeded: Int)
case OutOfStock
}
and
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.")
}
but I don't know how to do something similar for catching the errors of the standard Swift types that have methods using the throws
keyword.
The NSFileManager class reference for contentsOfDirectoryAtPath
doesn't say what kind of errors might be returned. So I don't know what errors to catch or how to handle them if I get them.
Update
I would like to do something like this:
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.")
}