exitcode.go 901 B

123456789101112131415161718192021222324252627282930313233
  1. package system
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "syscall"
  6. )
  7. // GetExitCode returns the ExitStatus of the specified error if its type is
  8. // exec.ExitError, returns 0 and an error otherwise.
  9. func GetExitCode(err error) (int, error) {
  10. exitCode := 0
  11. if exiterr, ok := err.(*exec.ExitError); ok {
  12. if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
  13. return procExit.ExitStatus(), nil
  14. }
  15. }
  16. return exitCode, fmt.Errorf("failed to get exit code")
  17. }
  18. // ProcessExitCode process the specified error and returns the exit status code
  19. // if the error was of type exec.ExitError, returns nothing otherwise.
  20. func ProcessExitCode(err error) (exitCode int) {
  21. if err != nil {
  22. var exiterr error
  23. if exitCode, exiterr = GetExitCode(err); exiterr != nil {
  24. // TODO: Fix this so we check the error's text.
  25. // we've failed to retrieve exit code, so we set it to 127
  26. exitCode = 127
  27. }
  28. }
  29. return
  30. }