From 5d5290759ae9d4595d9563f4f952103199207d0f Mon Sep 17 00:00:00 2001 From: Diana Flach Date: Fri, 10 Jul 2020 22:06:59 +0200 Subject: [PATCH] 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 --- README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.md b/README.md index 1484240d..683eba42 100644 --- a/README.md +++ b/README.md @@ -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 Flags provide modifiers to control how the action command operates.