0

Is there a way to find what exceptions are thrown by Foundation methods in Swift 3? In particular, I'm using the FileManager class to copy a file from the app bundle to the document directory. The copyItem method throws an exception if the destination file exists. How to catch that specific exception? The only way I've found is to parse the localizedDescription, which is ugly and likely not robust:

func copySampleReport() {
    let fileManager = FileManager()
    let reportName = "MyFile.txt"
    if let documentUrl = try? fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false), let reportUrl = Bundle.main.url(forResource: URL(fileURLWithPath: reportName).deletingPathExtension().lastPathComponent, withExtension: URL(fileURLWithPath: reportName).pathExtension) {
        debugPrint("Copying \(reportUrl) to \(documentUrl)")
        do {
            try fileManager.copyItem(at: reportUrl, to: documentUrl.appendingPathComponent(reportName))
            debugPrint("File copied succesfully!")
        }
        catch {
            if error.localizedDescription.range(of:"exists") != nil {
                debugPrint("File exists at destination")
            } else {
                debugPrint(error.localizedDescription)
            }
        }
    }
}
Wolfy
  • 1,445
  • 1
  • 14
  • 28
  • Take a look at http://stackoverflow.com/questions/31977738/how-to-find-the-kind-of-errors-a-method-may-throw-and-catch-them-in-swift and http://stackoverflow.com/questions/34877027/how-get-the-list-of-errors-thrown-by-a-function – Ryan H. Mar 22 '17 at 02:02
  • Also, Apple's [Using Swift with Cocoa and Objective-C (Swift 3.0.1)](https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) documentation has an example showing how to use the `CocoaError` struct in Foundation to isolate a specific error. See the section "Catching and Handling an Error". – Ryan H. Mar 22 '17 at 02:11

0 Answers0