Golang返回nil不返回nil

问题描述:

我创建了一个自定义错误类型来包装错误,以便更轻松地在Golang中进行调试。当有打印错误时它可以工作,但是现在引起了恐慌。

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.

演示

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.

预期的行为是,如果错误为nil,则应忽略该错误,不幸的是相反。

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")
}

我希望它能打印没有错误。相反,即使错误为nil,它也会打印发现的错误< nil>

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

if err != nil

正在将err变量与nil 错误进行比较,但实际上是nil *错误

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

将代码更改为

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

产生了预期的结果。