Handle multiple swift errors in one catch block

2019-03-05 12:55发布

问题:

I have a question about the swift error handling. In my swift Script I have to do multiple things with the FileManager that could throw an exception. Now my first thought was, to put them all in one do-catch block.

do {
    let fileManager = FileManager.default
    try fileManager.moveItem(atPath: destination, toPath: "\(destination).old")
    try fileManager.createDirectory(atPath: destination, withIntermediateDirectories: false)
    ...
} catch {
    print(error)
    exit(EXIT_FAILURE)
}

The problem now is, that I cannot determine in the catch block, which statement threw the error. The localizedDescription is not really helpful either ("Error while restoring backup!").

Also I cannot really find out, which type the thrown error is, because I don’t find anything to it in the FileManager documentation.

I guess a way that works, would be to put each statement in it‘s own nested do-catch block, but this looks in my opinion very messy and hard to read.

So my question is, if there is another way to determine the error type or the statement that threw it in the catch block or to find out, which error type each FileManager statement throws?

Thanks in advance, Jonas

回答1:

Firstly no you can't tell which statement threw the error you have to wrap each one in the do/catch block.

Secondly the documentation doesn't say which errors the functions throw so you just test for the ones that look correct like this:

do {
    let fileManager = FileManager.default
    try fileManager.moveItem(atPath: destination, toPath: "\(destination).old")
    try fileManager.createDirectory(atPath: destination, withIntermediateDirectories: false)
    ...
} catch CocoaError.fileNoSuchFile {
    // Code to handle this type of error
} catch CocoaError.fileWriteFileExists {
    // Code to handle this type of error
} catch {
    // Code to handle any error not yet handled
}