Skip to content

Commit

Permalink
feat: added custom error handler function
Browse files Browse the repository at this point in the history
  • Loading branch information
alexraileanu committed Jul 5, 2022
1 parent 69083f8 commit 17e813a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
21 changes: 19 additions & 2 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ type Command struct {
// versionTemplate is the version template defined by user.
versionTemplate string

// errorHandlerFunc allows setting a custom error handler by the user.
errorHandlerFunc func(error)

// inReader is a reader defined by the user that replaces stdin
inReader io.Reader
// outWriter is a writer defined by the user that replaces stdout
Expand Down Expand Up @@ -322,6 +325,12 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string
}
}

// SetErrorHandlerFunc is the function that will be called, if set, when there is any kind of error in the
// execution of the command.
func (c *Command) SetErrorHandlerFunc(f func(error)) {
c.errorHandlerFunc = f
}

// OutOrStdout returns output to stdout.
func (c *Command) OutOrStdout() io.Writer {
return c.getOut(os.Stdout)
Expand Down Expand Up @@ -970,7 +979,11 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
c = cmd
}
if !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
if c.errorHandlerFunc != nil {
c.errorHandlerFunc(err)
} else {
c.PrintErrln("Error:", err.Error())
}
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
}
return c, err
Expand Down Expand Up @@ -999,7 +1012,11 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// If root command has SilenceErrors flagged,
// all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
if c.errorHandlerFunc != nil {
c.errorHandlerFunc(err)
} else {
c.PrintErrln("Error:", err.Error())
}
}

// If root command has SilenceUsage flagged,
Expand Down
21 changes: 21 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cobra
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"os"
Expand Down Expand Up @@ -2193,3 +2194,23 @@ func TestSetContextPersistentPreRun(t *testing.T) {
t.Error(err)
}
}

func TestSetCustomErrorHandler(t *testing.T) {
var writer bytes.Buffer
handler := func(err error) {
writer.Write([]byte(err.Error()))
}

root := &Command{
Use: "root",
RunE: func(cmd *Command, args []string) error {
return errors.New("test error handler function")
},
SilenceUsage: true,
}
root.SetErrorHandlerFunc(handler)
_ = root.Execute()
if writer.String() != "test error handler function" {
t.Errorf("Expected error handler to contain [%s] instead it contains [%s]", "test error handler function", writer.String())
}
}

0 comments on commit 17e813a

Please sign in to comment.