From e98f4885a3102c888e4f5fd8ebce84375765ed38 Mon Sep 17 00:00:00 2001 From: Laura Brehm Date: Wed, 29 Jan 2025 17:02:03 +0100 Subject: [PATCH] Don't print "context canceled" if user terminated Without breaking API compatibility, this patch allows us to know whether a returned `cli/StatusError` was caused by a context cancellation or not, which we can use to provide a nicer UX and not print the Go "context canceled" error message if this is the cause. Signed-off-by: Laura Brehm --- cli/command/container/run.go | 3 +++ cli/error.go | 14 +++++++++++--- cmd/docker/docker.go | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/cli/command/container/run.go b/cli/command/container/run.go index 5ef3e8b7bf7b..ac780533bfd3 100644 --- a/cli/command/container/run.go +++ b/cli/command/container/run.go @@ -324,6 +324,7 @@ func toStatusError(err error) error { if strings.Contains(errMsg, "executable file not found") || strings.Contains(errMsg, "no such file or directory") || strings.Contains(errMsg, "system cannot find the file specified") { return cli.StatusError{ + Cause: err, Status: withHelp(err, "run").Error(), StatusCode: 127, } @@ -331,12 +332,14 @@ func toStatusError(err error) error { if strings.Contains(errMsg, syscall.EACCES.Error()) || strings.Contains(errMsg, syscall.EISDIR.Error()) { return cli.StatusError{ + Cause: err, Status: withHelp(err, "run").Error(), StatusCode: 126, } } return cli.StatusError{ + Cause: err, Status: withHelp(err, "run").Error(), StatusCode: 125, } diff --git a/cli/error.go b/cli/error.go index 8c4a5f952bce..1d35b4e77d65 100644 --- a/cli/error.go +++ b/cli/error.go @@ -6,6 +6,7 @@ import ( // StatusError reports an unsuccessful exit by a command. type StatusError struct { + Cause error Status string StatusCode int } @@ -14,8 +15,15 @@ type StatusError struct { // it is returned as-is, otherwise it generates a generic error-message // based on the StatusCode. func (e StatusError) Error() string { - if e.Status == "" { - return "exit status " + strconv.Itoa(e.StatusCode) + if e.Status != "" { + return e.Status } - return e.Status + if e.Cause != nil { + return e.Cause.Error() + } + return "exit status " + strconv.Itoa(e.StatusCode) +} + +func (e StatusError) Unwrap() error { + return e.Cause } diff --git a/cmd/docker/docker.go b/cmd/docker/docker.go index 2f927aa1e68d..3649f8a7ed2f 100644 --- a/cmd/docker/docker.go +++ b/cmd/docker/docker.go @@ -30,7 +30,7 @@ import ( func main() { err := dockerMain(context.Background()) - if err != nil && !errdefs.IsCancelled(err) { + if err != nil && !errdefs.IsCancelled(err) && !errors.Is(err, context.Canceled) { _, _ = fmt.Fprintln(os.Stderr, err) os.Exit(getExitCode(err)) }