Reducing nil check check boilerplate

Hello folks,

I’ve got lots of functions that get passed in some interface for operating on and have to do nil checks first:

func F(foo MyInterface, …) (something, error) {
if foo == nil {
return ErrParamNil
}

}

Is there any nice way for reducing the boilerplate here ?

thx.

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:

func CheckErr(msg interface{}) {
	if msg != nil {
		fmt.Fprintln(os.Stderr, "Error:", msg)
		os.Exit(1)
	}
}

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 …
  • go build
  • ./mycobracliapp newcommand
1 Like

Here’s a simple example straight from the standard library docs (https://pkg.go.dev/html/template).

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.)

func funcWithLocallySpecificErrorHandlingButUsedMultipleTimes() {	
	check := func(err error) {
			if err != nil {
				log.Fatal(err)
			}
		}

    _, err := errorReturningFunc()
    check(err)
    _, err := anotherErrorreturningFunc()
    check(err)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.