How to find the kind of errors a method may throw and catch them in Swift
It will return NSError:
let fileManager = NSFileManager()
do {
let docsArray = try fileManager.contentsOfDirectoryAtPath("/")
} catch let error as NSError {
// handle errors
print(error.localizedDescription)
// The file “Macintosh HD” couldn’t be opened because you don’t have permission to view it.
}
NSError
automatically bridges to ErrorType
where the domain becomes the type (e.g. NSCocoaErrorDomain
becomes CocoaError
) and the error code becomes the value (NSFileReadNoSuchFileError
becomes .fileNoSuchFile
)
import Foundation
let docsPath = "/file/not/found"
let fileManager = FileManager()
do {
let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch CocoaError.fileNoSuchFile {
print("No such file")
} catch let error {
// other errors
print(error.localizedDescription)
}
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 CocoaError
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) »