Handling nil with custom error

I started to use the go-error/error library to use stack-trace information.

Since error is an interface you can implement the interface in the error type and handle the struct as error. I got the problem to check if an error is nil when handling it as any error.

Here is an example that will panic. On line 15 i pass in ‘nil’ in the function, but inside the function it’s not nil anymore. Why?

to be honest I don’t have clue of what’s happens there but … I’ve added a println inside the printError function

func printError(e error) {
	if e != nil {
		println(fmt.Sprintf("%s", e.Error()))

and, when I run I see

works too
panic: value method main.MyErr.Error called using nil *MyErr pointer

An interface variable holds the concrete value that implements the interface (A Tour of Go). When you call a function that has an interface parameter with a value of an implementing type, the function sees an interface “wrapper” for the value. There’s a difference between a nil interface and an interface that contains a nil implementing value. This can lead to such confusion. A Tour of Go is similar but uses a method instead of a function that accepts an interface:

Note that an interface value that holds a nil concrete value is itself non-nil.


According to the suggestion made by @mje I fixed your code

1 Like