Skip to content

Commit

Permalink
fix(cdk): Avoid double component error messages (#1000)
Browse files Browse the repository at this point in the history
**Current Behavior:**

When running a component, if the component fails, we print two error
messages:
```
$ lacework iac fdsasd
Error: unknown command "fdsasd" for "iac"
ERROR unable to run component: exit status 1
```

**New Behavior:**

We detect that the error is a component failing to run and we avoid
outputting two error messages:
```
$ lacework iac fdsasd
Error: unknown command "fdsasd" for "iac"
```
  • Loading branch information
afiune committed Nov 2, 2022
1 parent d8f67d1 commit 363c1d4
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
8 changes: 8 additions & 0 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,18 @@ import (
"os"

"github.com/lacework/go-sdk/cli/cmd"
"github.com/lacework/go-sdk/lwcomponent"
)

func main() {
if err := cmd.Execute(); err != nil {
if componentError, ok := err.(*lwcomponent.RunError); ok {
// by default, all our components should display the error
// to the end user, which is why we don't output it, but we
// still exit the main program with the exit code from the component
os.Exit(componentError.ExitCode)
}

fmt.Fprintf(os.Stderr, "ERROR %s\n", err)
os.Exit(1)
}
Expand Down
26 changes: 25 additions & 1 deletion lwcomponent/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package lwcomponent

import "github.com/pkg/errors"
import (
"fmt"

"github.com/pkg/errors"
)

var (
ErrComponentNotFound = errors.New("component not found on disk")
Expand All @@ -13,3 +17,23 @@ var (
func IsNotFound(err error) bool {
return errors.Is(err, ErrComponentNotFound)
}

// RunError is a struct used to pass an error when a component tries to run and
// it fails, a few functions will return this error so that callers (upstream
// packages) can unwrap and identify that the error comes from this package
type RunError struct {
ExitCode int
Message string
Err error
}

func (e *RunError) Error() string {
if e.ExitCode == 0 {
return ""
}
return fmt.Sprintf("%s: %s", e.Message, e.Err.Error())
}

func (e *RunError) Unwrap() error {
return e.Err
}
11 changes: 10 additions & 1 deletion lwcomponent/executable.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,17 @@ func (c Component) run(cmd *exec.Cmd) error {
}

if err := cmd.Run(); err != nil {
return errors.Wrap(err, baseRunErr)
// default to -1 in case we can't get the actual exit code, which
// is better than returning an error with exit code 0 (default int)
exitCode := -1

if exitError, ok := err.(*exec.ExitError); ok {
exitCode = exitError.ExitCode()
}

return &RunError{Err: err, Message: baseRunErr, ExitCode: exitCode}
}

return nil
}

Expand Down

0 comments on commit 363c1d4

Please sign in to comment.