Suragch Suragch - 2 years ago 153
iOS Question

How to find the kind of errors a method may throw and catch them in Swift

I am using

to get an array of file names in a directory. I want to use the new
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
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


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

The NSFileManager class reference for
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.


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.")

Answer Source

NSError automatically bridges to ErrorType where the domain becomes the type (e.g. NSCocoaErrorDomain becomes NSCocoaError) and the error code becomes the value (NSFileReadNoSuchFileError becomes .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

As for knowing which error can be returned by a specific call, only the documentation can help. Almost all Foundation errors are part of the NSCocoaError domain and can be found in FoundationErrors.h (though there are some rare bugs where Foundation can also sometimes return POSIX errors under NSPOSIXErrorDomain) but these ones might not have been fully bridged so you will have to fall back on managing them at the NSError level.

More information can be found in « Using Swift with Cocoa and Objective-C (Swift 2.2) »

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download