Skip to content

Commit

Permalink
use specific errors with exit codes
Browse files Browse the repository at this point in the history
  • Loading branch information
alexzielenski committed Aug 15, 2023
1 parent 1677810 commit f810192
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
13 changes: 12 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import (
func main() {
rootCmd := cmd.NewRootCommand()
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
switch err.(type) {
case cmd.ValidationError:
os.Exit(1)
case cmd.ArgumentError:

Check failure on line 15 in main.go

View workflow job for this annotation

GitHub Actions / golangci-lint

SA4020: unreachable case clause: sigs.k8s.io/kubectl-validate/pkg/cmd.ValidationError will always match before sigs.k8s.io/kubectl-validate/pkg/cmd.ArgumentError (staticcheck)
os.Exit(2)
case cmd.InternalError:

Check failure on line 17 in main.go

View workflow job for this annotation

GitHub Actions / golangci-lint

SA4020: unreachable case clause: sigs.k8s.io/kubectl-validate/pkg/cmd.ValidationError will always match before sigs.k8s.io/kubectl-validate/pkg/cmd.InternalError (staticcheck)
os.Exit(3)
default:
// This case should not get hit, but in case it does,
// Treat unknown error as internal error
os.Exit(3)
}
}
}
7 changes: 7 additions & 0 deletions pkg/cmd/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package cmd

type ArgumentError error

type ValidationError error

type InternalError error
8 changes: 4 additions & 4 deletions pkg/cmd/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,12 @@ func (c *commandFlags) Run(cmd *cobra.Command, args []string) error {
),
)
if err != nil {
return err
return ArgumentError(err)
}

files, err := utils.FindFiles(args...)
if err != nil {
return err
return ArgumentError(err)
}

hasError := false
Expand Down Expand Up @@ -252,13 +252,13 @@ func (c *commandFlags) Run(cmd *cobra.Command, args []string) error {
}
data, e := json.MarshalIndent(res, "", " ")
if e != nil {
return fmt.Errorf("failed to render results into JSON: %w", e)
return InternalError(fmt.Errorf("failed to render results into JSON: %w", e))
}
fmt.Fprintln(cmd.OutOrStdout(), string(data))
}

if hasError {
return errors.New("validation failed")
return ValidationError(errors.New("validation failed"))
}
return nil
}
Expand Down

0 comments on commit f810192

Please sign in to comment.