如何处理Process.run抛出的异常?

3
根据可用的 API 和 Apple DocumentationProcess.run 方法可能会抛出异常。我想处理潜在的异常,但是找不到任何关于这些异常的文档。
如何找到相关的文档并处理 Process.run 异常?
示例代码:
func runProcess(process: Process) {
    do {
        try process.run()
    } catch ??? {
        // I don't know what exceptions can I catch here
    } catch {
        // If I use catch-all case, then the `error` object contains only
        // `localizedDescription` which doesn't help in handling errors either
    }
}
1个回答

2

它实际上是从[NSTask - (BOOL)launchAndReturnError:(out NSError **_Nullable)error]桥接而来的,所以抛出的异常是NSError,因此您可以从这里开始。

func runProcess(process: Process) {
    do {
        try process.run()
    } catch let error as NSError {
        // process NSError.code (domain, etc)
    } catch {
       // do anything else
    }
}

如果涉及到具体的代码,可能可以通过CocoaError来处理(那里有很多已声明的常量)。
/// Describes errors within the Cocoa error domain.
public struct CocoaError {
do {
    try process.run()
} catch CocoaError.fileNoSuchFile {
    print("Error: no such file exists")
}

以下是相关文档:

在Swift中处理Cocoa错误

Cocoa错误常量


1
第一个示例中的“做任何其他事情”情况是不必要的,每个 Error 都可以转换为 NSError - Martin R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接