Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch error when setting launchpath in NSTask

I am trying to run a commandline tool using swift 2 on a mac (10.10):

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")
}

Since the path is wrong, my program dies with launch path not accessible. However, I don't know, how to catch this error. Using do { try } catch {} around task.launch() does not work, because it does not throw an exception, looking at the terminationStatus is also not working, since it is never reached.

How can I catch a wrong launchPath?

Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81) Target: x86_64-apple-darwin14.5.0

like image 767
Gregsen Avatar asked Dec 22 '15 16:12

Gregsen


2 Answers

In Mac OS X High Sierra, launch() is deprecated. You would use run() instead:

let process = Process()
// ...

do {
    process.run()
} catch let error as NSError {
    print(error.localizedDescription)
    // ...
}

Also have a look at the Apple Dev Docs

like image 82
j3141592653589793238 Avatar answered Sep 21 '22 11:09

j3141592653589793238


unfortunately, there is no chance to catch runtime exceptions. with try / catch you can recovery from trowing error, not from runtime exception. you can create you own exception handler, but you are still not able to recover from it. try to lunch from NSTask some common shell with command as a parameter and next use a pipe to return os errors to you own code.

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 ?? "")

will print

/bin/bash: unknown: command not found
like image 25
user3441734 Avatar answered Sep 22 '22 11:09

user3441734