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

How can I handle exceptions that Process.run throws

根据可用 API 和 Apple Documentation Process.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
    }
}

其实是从[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")
}

这里是相关文档:

Handling Cocoa Errors in Swift

CocoaError constants