gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:40:04 29 4
gpt4 key购买 nike

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

关于swift - 如何处理 Process.run 抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60157321/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com