【问题标题】:How can I handle exceptions that Process.run throws如何处理 Process.run 抛出的异常
【发布时间】:2020-02-10 19:42:39
【问题描述】:

根据可用的 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
    }
}

【问题讨论】:

    标签: swift macos cocoa exception process


    【解决方案1】:

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

    【讨论】:

    • 不需要第一个示例中的“做任何其他事情”的情况,每个 Error 可以桥接到NSError。
    猜你喜欢
    • 2019-03-20
    • 1970-01-01
    • 2013-07-24
    • 2022-11-25
    • 2021-12-22
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多