mirror of
https://github.com/spf13/cobra
synced 2024-11-16 18:57:08 +00:00
adds alternative error handling to readme
This commit is contained in:
parent
230787ee13
commit
028f9e5eb8
1 changed files with 45 additions and 4 deletions
43
README.md
43
README.md
|
@ -418,6 +418,48 @@ func main() {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Alternative Error Handling
|
||||||
|
|
||||||
|
Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:
|
||||||
|
|
||||||
|
* PersistentPreRunE
|
||||||
|
* PreRunE
|
||||||
|
* RunE
|
||||||
|
* PostRunE
|
||||||
|
* PersistentPostRunE
|
||||||
|
|
||||||
|
**Example Usage using RunE:**
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var rootCmd = &cobra.Command{
|
||||||
|
Use: "hugo",
|
||||||
|
Short: "Hugo is a very fast static site generator",
|
||||||
|
Long: `A Fast and Flexible Static Site Generator built with
|
||||||
|
love by spf13 and friends in Go.
|
||||||
|
Complete documentation is available at http://hugo.spf13.com`,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
// Do Stuff Here
|
||||||
|
return errors.New("some random error")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Suggestions when "unknown command" happens
|
## Suggestions when "unknown command" happens
|
||||||
|
|
||||||
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behavior similarly to the `git` command when a typo happens. For example:
|
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behavior similarly to the `git` command when a typo happens. For example:
|
||||||
|
@ -522,4 +564,3 @@ Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github
|
||||||
|
|
||||||
|
|
||||||
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
|
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue