-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Correct pattern for exiting a command with a non zero return code #2124
Comments
This almost gives me what I want:
The SetFlagErrorFunc allows a hook when the error is caused by bad flags, but that doesn't get fired for invalid arguments other than flags (so validation done by the "Args" field in Command). Then use RunE, so you can return an error from the command and it will cause a non zero return code. This has always somewhat surprised me in cobra. I'd have thought that the normal desired behaviour would be "invalid flags or args or command name, print error then usage, errors from the command, just print error". I've always slightly struggled to get that behaviour. |
I'm using |
Let me analyze the error. When cobra command returns an error, cobra prints help message. package main
import (
"errors"
"os"
"github.com/spf13/cobra"
)
var ErrorExit = errors.New("ErrorExit")
func main() {
rootCmd := &cobra.Command{
RunE: func(cmd *cobra.Command, ards []string) error {
return ErrorExit
},
}
if err := rootCmd.Execute(); err != nil {
if err == ErrorExit {
os.Exit(1)
}
}
} Error: ErrorExit
Usage:
[flags]
Flags:
-h, --help help for this command
exit status 1 |
Undocumented https://go.dev/play/p/1oR9hP8Ix42
With and without To force print usage, need to return |
I'm trying to establish what the correct pattern is for exiting a command with a non zero return code.
I can use RunE, but the normal effect of that is that the "usage" is printed out, since there's no distinction between an error from validating the args (where you would want usage to result) and an error from the operation of your command. You can SilenceUsage, but then you get no usage help on invalid args either, so that doesn't feel like the right way.
The examples generated by the CLI all use Run instead of RunE. The implication would appear to be that I have to manually os.Exit(1) if I want my command to "fail" and return a non zero return code. But that feels wrong, it's going to skip all of the post run actions etc.
Looking at a couple of examples, it seems like managing an exit code outside of cobra seems to be a solution used in a few places, so letting the command run to completion and then once cobra has returned calling os.Exit() with the value that's stored in some global variable somewhere.
What's the idiomatic usage here?
Thanks
The text was updated successfully, but these errors were encountered: