Skip to content

Commit

Permalink
Simplify wrapError
Browse files Browse the repository at this point in the history
  • Loading branch information
lpusok committed May 15, 2024
1 parent d60e4f9 commit ba15e33
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
10 changes: 5 additions & 5 deletions command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,14 @@ func printableCommandArgs(isQuoteFirst bool, fullCommandArgs []string) string {
func (c command) wrapError(err error) error {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if c.errorCollector != nil && len(c.errorCollector.errorLines) > 0 {
reason := fmt.Errorf("command failed with exit status %d (%s): %w", exitErr.ExitCode(), c.PrintableCommandArgs(), errors.New(strings.Join(c.errorCollector.errorLines, "\n")))
return NewExitStatusError(reason, exitErr)
errorLines := []string{}
if c.errorCollector != nil {
errorLines = c.errorCollector.errorLines
}

reason := fmt.Errorf("command failed with exit status %d (%s): %w", exitErr.ExitCode(), c.PrintableCommandArgs(), errors.New("check the command's output for details"))
return NewExitStatusError(reason, exitErr)
return NewExitStatusError(c.PrintableCommandArgs(), exitErr, errorLines)
}

return fmt.Errorf("executing command failed (%s): %w", c.PrintableCommandArgs(), err)
}

Expand Down
18 changes: 13 additions & 5 deletions command/errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package command

import "os/exec"
import (
"errors"
"fmt"
"os/exec"
"strings"
)

// ExitStatusError ...
type ExitStatusError struct {
Expand All @@ -9,12 +14,15 @@ type ExitStatusError struct {
}

// NewExitStatusError ...
func NewExitStatusError(reasonErr error, originalExitErr *exec.ExitError) error {
if reasonErr.Error() == "" {
panic("reason must not be empty")
func NewExitStatusError(printableCmdArgs string, exitErr *exec.ExitError, errorLines []string) error {
reasonMsg := fmt.Sprintf("command failed with exit status %d (%s)", exitErr.ExitCode(), printableCmdArgs)
if len(errorLines) == 0 {
reasonErr := fmt.Errorf("%s: %w", reasonMsg, errors.New("check the command's output for details"))
return &ExitStatusError{readableReason: reasonErr, originalCommandErr: exitErr}
}

return &ExitStatusError{readableReason: reasonErr, originalCommandErr: originalExitErr}
reasonErr := fmt.Errorf("%s: %w", reasonMsg, errors.New(strings.Join(errorLines, "\n")))
return &ExitStatusError{readableReason: reasonErr, originalCommandErr: exitErr}
}

// Error returns the formatted error message. Does not include the original error message (`exit status 1`).
Expand Down

0 comments on commit ba15e33

Please sign in to comment.