Last active
April 6, 2022 06:47
-
-
Save blackandred/c77a6b83d4d5c6e662ba19b1618b75b7 to your computer and use it in GitHub Desktop.
Cancel Context, when exec.Command{} process fails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ReadCloserWithCancellationWhenProcessFails struct { | |
Parent io.ReadCloser | |
Process *exec.Cmd | |
Cancel func() | |
} | |
func (r ReadCloserWithCancellationWhenProcessFails) Read(p []byte) (n int, err error) { | |
return r.Parent.Read(p) | |
} | |
func (r ReadCloserWithCancellationWhenProcessFails) Close() error { | |
err := r.Process.Wait() | |
exitCode := 0 | |
if err != nil { | |
// try to get the exit code | |
if exitError, ok := err.(*exec.ExitError); ok { | |
ws := exitError.Sys().(syscall.WaitStatus) | |
exitCode = ws.ExitStatus() | |
} else { | |
exitCode = 1 | |
} | |
} else { | |
ws := r.Process.ProcessState.Sys().(syscall.WaitStatus) | |
exitCode = ws.ExitStatus() | |
} | |
if exitCode > 0 { | |
log.Errorf("Canceling upload due to process failure - exitCode: %v", exitCode) | |
r.Cancel() | |
} | |
return r.Parent.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment