在一个catch块中处理多个快速错误 [英] Handle multiple swift errors in one catch block

查看:94
本文介绍了在一个catch块中处理多个快速错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对快速错误处理有疑问。在我的快捷脚本中,我必须对FileManager进行多项操作,这可能会引发异常。现在我的第一个想法是,将它们全部放入一个do-catch块中。

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)
}

现在的问题是,我无法在catch块中确定哪个语句引发了错误。 localizedDescription也没有真正的帮助(还原备份时出错!。)。

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

我也无法真正找出抛出错误的类型,因为我不知道在FileManager文档中找不到任何内容。

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

我想一种可行的方法是将每个语句放入其自己的嵌套do-catch块中,但是

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.

所以我的问题是,是否还有其他方法可以确定错误类型或将错误类型放入语句中catch块还是找出每个FileManager语句会抛出哪种错误类型?

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?

在此先感谢
Jonas

Thanks in advance, Jonas

推荐答案

首先,不能,您不能告诉哪个语句引发了错误,您必须将每个语句包装在do / catch块中。

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
}

这篇关于在一个catch块中处理多个快速错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆