不能使用errors.New("错误")(类型错误)作为返回参数中的类型错误

时间:2014-10-23 09:52:19

标签: go

我有以下代码(http://play.golang.org/p/47rvtGqGFn)。它适用于游乐场但在我的系统上失败

 package main

import (
   "log"
   "errors" 
)

func main() {
    j := &JustForTest{}
    a, err := j.Test(3)
    if err != nil {
        log.Println(err)
    }
    log.Println(a)
}

type JustForTest struct {}

func (j *JustForTest) Test(i int) (string, error) {
    if i < 5 {
        return "fail", errors.New("something wrong")
    }
    return "success", nil
}

在操场上它会返回我期望的东西:

2009/11/10 23:00:00 something wrong
2009/11/10 23:00:00 fail

但是当我跑步&#34;去安装&#34;在我的系统上,我收到编译器错误:

../warehouse/warehouse.go:32: cannot convert nil to type error
../warehouse/warehouse.go:83: cannot use errors.New("something wrong") (type error) as type error in return argument
../warehouse/warehouse.go:85: cannot use nil as type error in return argument

我觉得这很奇怪。我已将我的Go安装从1.3.2升级到1.3.3但仍然得到相同的错误。我的系统可能出现什么问题?

更新 这是我的本地代码:

package warehouse

import (
    "net/http"
    "path"
    "log"
    "errors"
)


func Route(w http.ResponseWriter, r *http.Request) {


    uri := path.Dir(r.URL.Path)

    base := path.Base(r.URL.Path)
    if uri == "/" || (uri == "/products" && base != "products") {
        uri = path.Join(uri, base)
    }

    // initiate all types
    warehouse := Warehouse{}
    inventory := Inventory{}

    // check the request method
    if r.Method == "GET" {
        switch uri {
        case "/warehouse":
            j := &JustForTest{}     // This is the troubled code
            a, err := j.Test(3)
            if err != nil {
                log.Println(err)
            }
            log.Println(a)
            ...
       }
} 

type JustForTest struct {}

func (j *JustForTest) Test(i int) (string, error) {
    if i < 5 {
        return "fail", errors.New("something wrong")
    }
    return "success", nil
}

我发现当我运行此代码时,我收到错误。但是,当我写一个新的新包时,只需编写与我在plaground中完全相同的代码。有用。我不明白为什么会这样。任何建议的人?

2 个答案:

答案 0 :(得分:2)

您的软件包中似乎已定义了一个名为error的类型。

这导致与内置error类型的名称冲突(您的包定义类型会影响内置类型),从而导致您看到的令人困惑的错误消息。

为包的类型使用不同的,更具描述性(不太通用的)名称。

答案 1 :(得分:1)

除@tomwilde响应外,我还建议使用fmt.Errorf()函数来构建错误。您还需要添加&#34; fmt&#34;的导入。包,可以删除导入&#34;错误&#34;封装

您的代码可以改为:

if i < 5 {
    return "fail", errors.New("something wrong")
}

致:

if i < 5 {
    return "fail", fmt.Errorf("something wrong")
}

使用fmt.Errorf()方法的优点是您还可以提供格式化来构建错误消息,这在将来可能非常方便,例如: fmt.Errorf("some error .... %#v", aValue)

我希望这会有所帮助。

相关问题