Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle exceptions that Process.run throws

According to the available API and Apple Documentation Process.run method may throw exceptions. I'd like to handle the potential exceptions, but I can't find any documentation on what these exception can be.

How can I find relevant documentation and handle Process.run exceptions?

Example code:

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
    }
}
like image 296
Alex Avatar asked Feb 27 '26 15:02

Alex


1 Answers

It is actually bridged from [NSTask - (BOOL)launchAndReturnError:(out NSError **_Nullable)error], so the thrown exception is NSError, so you can start from

func runProcess(process: Process) {
    do {
        try process.run()
    } catch let error as NSError {
        // process NSError.code (domain, etc)
    } catch {
       // do anything else
    }
}

If it is interested specific code it might be handled via CocoaError (there are a lot of declared constants there)

/// Describes errors within the Cocoa error domain.
public struct CocoaError {
do {
    try process.run()
} catch CocoaError.fileNoSuchFile {
    print("Error: no such file exists")
}

Here is related documentation:

Handling Cocoa Errors in Swift

CocoaError constants

like image 59
Asperi Avatar answered Mar 02 '26 05:03

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!