I\'m using the package: os/exec http://golang.org/pkg/os/exec/ to execute a command in the operating system but I don\'t seem to find the way to get the exit code. I can rea
September 2019, Go 1.13 introduced errors.As which supports error "unwrapping" - handy for finding precise errors in a nested call-chain.
So to extract and inspect the two most common errors when running an external command:
err := cmd.Run()
var (
ee *exec.ExitError
pe *os.PathError
)
if errors.As(err, &ee) {
log.Println("exit code error:", ee.ExitCode()) // ran, but non-zero exit code
} else if errors.As(err, &pe) {
log.Printf("os.PathError: %v", pe) // "no such file ...", "permission denied" etc.
} else if err != nil {
log.Printf("general error: %v", err) // something really bad happened!
} else {
log.Println("success!") // ran without error (exit code zero)
}