Usually one would recommend against doing this.
It’s simply a Go-idiom with the philosophy that you should do something sensible with your errors at the place they occur.
For example:
In the code-generator application github.com/spf13/cobra-cli (which is personally not my favorite because I think it’s a bit bloated) which generates code that the github.com/spf13/cobra-library uses (“for all your CLI-needs”), we can find this function:
I wouldn’t recommend exactly copying this but there are very creative ways to handle errors. I’m always curious to learn interesting ways different projects use errors, do any other people know nice examples?
Since I was trying out the latest version of cobra myself while writing this post, I will just leave the steps here:
go get github.com/spf13/cobra-cli@latest
mkdir work
cd work
cobra-cli help
cobra-cli init --pkgname mymymynick/mycobracliapp
cd mycobracliapp
check the generated code in root.go where the cobra.CheckErr-function is called
cobra add newcommand
the file work/mycobracliapp/cmd/newcommand.go is now created and you can add your own code in the Run-field of the cobra.Command-struct-literal. This code will be ran when you …
It is useful if you want to define an error handler locally in a function.
This is done by assigning an anonymous function func(err error) to the check-variable. (Which is possible thanks to Go supporting functions as values.)