在NSTask中设置launchpath时如何捕获错误

Gre*_*sen 7 command-line-interface swift swift2

我试图在mac(10.10)上使用swift 2运行命令行工具:

let task = NSTask()
task.launchPath = "/path/to/wrong/binary"
task.launch()

// NSPipe() stuff to catch output

task.waitUntilExit()

// never reached
if (task.terminationStatus != 0){
    NSLog("uh oh")
}
Run Code Online (Sandbox Code Playgroud)

由于路径错误,我的程序就死了launch path not accessible.但是,我不知道,如何捕捉到这个错误.使用do { try } catch {}around task.launch()不起作用,因为它不会抛出异常,看着terminationStatus它也无法正常工作,因为它永远不会到达.

我怎么能弄错launchPath

Apple Swift版本2.1.1(swiftlang-700.1.101.15 clang-700.1.81)目标:x86_64-apple-darwin14.5.0

use*_*734 3

不幸的是,没有机会捕获运行时异常。使用 try / catch 您可以从拖拽错误中恢复,而不是从运行时异常中恢复。您可以创建自己的异常处理程序,但仍然无法从中恢复。尝试从 NSTask 中使用命令作为参数的一些常见 shell,然后使用管道将操作系统错误返回到您自己的代码。

import Foundation

let task = Process()
let pipe = Pipe()
task.launchPath = "/bin/bash"
task.arguments = ["-c","unknown"]
task.standardOutput = pipe
task.launch()
let handle = pipe.fileHandleForReading
let data = handle.readDataToEndOfFile()
let dataString = String(data: data, encoding: .utf8)
print(dataString ?? "")
Run Code Online (Sandbox Code Playgroud)

将打印

/bin/bash: unknown: command not found
Run Code Online (Sandbox Code Playgroud)