Skip to content

Instantly share code, notes, and snippets.

@eparis
Created August 30, 2015 16:04
Show Gist options
  • Save eparis/be6ca4c767e69fcaaea8 to your computer and use it in GitHub Desktop.
Save eparis/be6ca4c767e69fcaaea8 to your computer and use it in GitHub Desktop.
cobra Run function with errors
diff --git a/command.go b/command.go
index cbbc326..9e4518f 100644
--- a/command.go
+++ b/command.go
@@ -70,6 +70,9 @@ type Command struct {
PreRun func(cmd *Command, args []string)
// Run: Typically the actual work function. Most commands will only implement this
Run func(cmd *Command, args []string)
+ // RunE: Typically the actual work function. Most commands will only implement this
+ // Same as Run but return an error. If both as set, RunE will be used
+ RunE func(cmd *Command, args []string) error
// PostRun: run after the Run command.
PostRun func(cmd *Command, args []string)
// PersistentPostRun: children of this command will inherit and execute after PostRun
@@ -473,7 +476,13 @@ func (c *Command) execute(a []string) (err error) {
c.PreRun(c, argWoFlags)
}
- c.Run(c, argWoFlags)
+ if c.RunE != nil {
+ if err := c.RunE(c, argWoFlags); err != nil {
+ return err
+ }
+ } else {
+ c.Run(c, argWoFlags)
+ }
if c.PostRun != nil {
c.PostRun(c, argWoFlags)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment