From a5c990d57019ff4789e587888a08300075ed4e66 Mon Sep 17 00:00:00 2001 From: Michael Feher Date: Thu, 16 Jan 2025 12:20:17 -0500 Subject: [PATCH] fix: improve command error handling resolves #106 --- cmd/utils/flags.go | 4 ++-- internal/system/cmds.go | 23 ++++++++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index e41e6987..0261c708 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1,6 +1,7 @@ package utils import ( + "fmt" "github.com/algorandfoundation/nodekit/api" "github.com/algorandfoundation/nodekit/cmd/utils/explanations" "github.com/algorandfoundation/nodekit/internal/algod" @@ -20,8 +21,7 @@ func WithInvalidResponsesExplanations(err error, response api.ResponseInterface, } if response.StatusCode() > 300 { log.Fatal( - style.Red.Render("failed to get status: error code %d")+"\n\n"+explanations.TokenNotAdmin+"\n"+postFix, - response.StatusCode()) + style.Red.Render(fmt.Sprintf("failed to get status: error code %d", response.StatusCode())) + "\n\n" + explanations.TokenNotAdmin + "\n" + postFix) } } diff --git a/internal/system/cmds.go b/internal/system/cmds.go index fba2afd1..b13b566b 100644 --- a/internal/system/cmds.go +++ b/internal/system/cmds.go @@ -1,6 +1,7 @@ package system import ( + "errors" "fmt" "github.com/algorandfoundation/nodekit/ui/style" "github.com/charmbracelet/log" @@ -11,9 +12,6 @@ import ( "sync" ) -// CmdFailedErrorMsg is a formatted error message used to detail command failures, including output and the associated error. -const CmdFailedErrorMsg = "command failed: %s output: %s error: %v" - // IsSudo checks if the process is running with root privileges by verifying the effective user ID is 0. func IsSudo() bool { return os.Geteuid() == 0 @@ -60,9 +58,24 @@ func RunAll(list CmdsList) error { log.Debug(fmt.Sprintf("%s: %s", style.Green.Render("Running"), strings.Join(args, " "))) cmd := exec.Command(args[0], args[1:]...) output, err := cmd.CombinedOutput() + if err != nil { - log.Error(fmt.Sprintf("%s: %s", style.Red.Render("Failed"), strings.Join(args, " "))) - return fmt.Errorf(CmdFailedErrorMsg, strings.Join(args, " "), output, err) + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + // Get Stderr when possible + if exitErr.Stderr != nil { + log.Error(exitErr.Stderr) + } else { + // Report the output + log.Error(strings.TrimSuffix(string(output), "\n")) + } + + } else { + // Log the regular errors + log.Error(err) + } + // Alert the User + return fmt.Errorf("%s: %s", style.Red.Render("Failed"), strings.Join(args, " ")) } }