diff --git a/command.go b/command.go index 42e500de..b8d24aca 100644 --- a/command.go +++ b/command.go @@ -114,6 +114,8 @@ type Command struct { PersistentPostRun func(cmd *Command, args []string) // PersistentPostRunE: PersistentPostRun but returns an error. PersistentPostRunE func(cmd *Command, args []string) error + // OnCommandNotFound: custom CommandNotFound handler + OnCommandNotFound func (cmd *Command, args []string) // SilenceErrors is an option to quiet errors down stream. SilenceErrors bool @@ -903,8 +905,13 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { c = cmd } if !c.SilenceErrors { - c.Println("Error:", err.Error()) - c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) + if c.OnCommandNotFound != nil { + c.OnCommandNotFound(c, args) + return c, nil + } else { + c.Println("Error:", err.Error()) + c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) + } } return c, err } diff --git a/command_test.go b/command_test.go index b26bd4ab..94058b93 100644 --- a/command_test.go +++ b/command_test.go @@ -147,6 +147,19 @@ func TestRootUnknownCommandSilenced(t *testing.T) { } } +func TestRootUnknownCommandCustomHandler(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.OnCommandNotFound = func(cmd *Command, args []string) { + cmd.Println("Command not found. Sorry buddy :(") + } + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, _ := executeCommand(rootCmd, "unknown") + if output != "Command not found. Sorry buddy :(\n" { + t.Errorf("Expected custom output message, because of custom CommandNotFound handler.\nGot:\n %q\n", output) + } +} + func TestCommandAlias(t *testing.T) { var timesCmdArgs []string rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}