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) {
	println(e)
	if e != nil {
		println(fmt.Sprintf("%s", e.Error()))
	}
}

and, when I run I see

(0x0,0x0)
works
(0x0,0x0)
works too
0x0
(0x4b2af8,0x0)
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.

2 Likes

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

1 Like

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