diff --git a/command.go b/command.go index 34d1bf36..37a7d288 100644 --- a/command.go +++ b/command.go @@ -195,6 +195,8 @@ type Command struct { helpCommand *Command // versionTemplate is the version template defined by user. versionTemplate string + // errorTemplate is the error template defined by user. + errorTemplate string } // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden @@ -219,6 +221,11 @@ func (c *Command) SetUsageTemplate(s string) { c.usageTemplate = s } +// SetErrorTemplate sets error template to be used. Application can use it to set custom template. +func (c *Command) SetErrorTemplate(s string) { + c.errorTemplate = s +} + // SetFlagErrorFunc sets a function to generate an error when flag parsing // fails. func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { @@ -434,6 +441,18 @@ func (c *Command) HelpTemplate() string { {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` } +// ErrorTemplate return error template for the command. +func (c *Command) ErrorTemplate() string { + if c.errorTemplate != "" { + return c.errorTemplate + } + + if c.HasParent() { + return c.parent.ErrorTemplate() + } + return "Error: {{ .Error }}\n" +} + // VersionTemplate return version template for the command. func (c *Command) VersionTemplate() string { if c.versionTemplate != "" { @@ -838,7 +857,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { c = cmd } if !c.SilenceErrors { - c.Println("Error:", err.Error()) + tmpl(c.OutOrStdout(), c.ErrorTemplate(), err) c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) } return c, err @@ -861,7 +880,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // If root command has SilentErrors flagged, // all subcommands should respect it if !cmd.SilenceErrors && !c.SilenceErrors { - c.Println("Error:", err.Error()) + tmpl(c.OutOrStdout(), c.ErrorTemplate(), err) } // If root command has SilentUsage flagged, diff --git a/command_test.go b/command_test.go index ccee031d..62fa2377 100644 --- a/command_test.go +++ b/command_test.go @@ -866,6 +866,16 @@ func TestVersionTemplate(t *testing.T) { checkStringContains(t, output, "customized version: 1.0.0") } +func TestErrorTemplate(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + rootCmd.SetErrorTemplate(`customized error: {{ . }}`) + + output, _ := executeCommand(rootCmd, "unknown") + + checkStringContains(t, output, "customized error: unknown command") +} + func TestVersionFlagExecutedOnSubcommand(t *testing.T) { rootCmd := &Command{Use: "root", Version: "1.0.0"} rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})