Cannot use errors.New ("something is wrong") (type error) as type error in return argument
I have the following code ( http://play.golang.org/p/47rvtGqGFn ). it works on playground but doesn't work on my system.
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
}
in the playground, it returns what I was expecting:
2009/11/10 23:00:00 something wrong 2009/11/10 23:00:00 fail
But when I run "go install" on my system, I get a compiler error:
../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
I feel like this is really weird. I upgrade my Go installation from 1.3.2 to 1.3.3 but still get the same error. What could be wrong with my system?
UPDATE: Here is my local code:
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
}
I found that when I run this code, I get an error. But when I write a new fresh package and just write exactly the same code as in plaground. it works. I don't understand why this is happening. any advice guys?
source to share
It looks like you have defined a type in your package error
.
This causes a name clash with the built-in type error
(your package-defined type obscures the built-in type) and hence the confusing error message you see.
Use a different, more descriptive (less general) name for your package type.
source to share
In addition to @ tomwilde's answer, I would recommend using a function fmt.Errorf()
to generate errors. You will also need to add the import of the "fmt" package and remove the import of the "errors" package.
Your code can be changed:
if i < 5 {
return "fail", errors.New("something wrong")
}
To:
if i < 5 {
return "fail", fmt.Errorf("something wrong")
}
The advantage of using the approach fmt.Errorf()
is that you can also provide formatting to generate the error message, which can be very handy in the future, eg.fmt.Errorf("some error .... %#v", aValue)
I hope this helps.
source to share