Golang returning nil does not return nil

Issue

I created a custom error type to wrap errors around for easier debugging in Golang. It works when there are errors to print, but now it is causing a panic.

Demo

type Error struct {
    ErrString string
}

func (e *Error) Error() string {
    return e.ErrString
}

func Wrap(err error, str string) *Error {
    if err == nil {
        return nil
    }
    e := &Error{
        ErrString: str + err.Error(),
    }
    return e
}

When I call a function an it doesn’t return an error, I should still be able to wrap the error.

The expected behavior is that if the error is nil, it should simply ignore it, unfortunately it does the opposite.

func foo() error {
    err := bar()
    return Wrap(err, "bar called")
}

func bar() error {
    return nil
}

func main() {
    err := foo()
    if err != nil {
        fmt.Printf("Found error %v\n",err)
        return
    }
    fmt.Println("No Errors")
}

I expect it to print No errors. Instead it prints Found error <nil> even though the error is nil.

Solution

if err != nil

Is comparing a the err variable to a nil error , but its actually a nil *Error

Changing the code to

err:=foo()
var  nilerror *Error = nil
if err != nilerror {
    fmt.Printf("Found error %v\n",err)
    return
}
fmt.Println("No Errors")

Yields the predicted result.

Answered By – pigeonhands

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.