Update README.md (#1154)

I found this through a comment on an issue and thought this might save someone some time looking through the code.

fixes #1148
This commit is contained in:
Diana Flach 2020-07-10 22:06:59 +02:00 committed by GitHub
parent 207dc47664
commit 5d5290759a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -312,6 +312,37 @@ var versionCmd = &cobra.Command{
} }
``` ```
### Returning and handling errors
If you wish to return an error to the caller of a command, `RunE` can be used.
```go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
func init() {
rootCmd.AddCommand(tryCmd)
}
var tryCmd = &cobra.Command{
Use: "try",
Short: "Try and possibly fail at something",
RunE: func(cmd *cobra.Command, args []string) error {
err := someFunc()
if err := nil {
return err
}
},
}
```
The error can then be caught at the execute function call.
## Working with Flags ## Working with Flags
Flags provide modifiers to control how the action command operates. Flags provide modifiers to control how the action command operates.