gogo-testing

Why do I get "second argument to errors.As should not be *error" build error in test only?


Consider the following test:

import (
    "errors"
    "fmt"
    "testing"
)

func TestError(t *testing.T) {
    err := &MyError{}
    var target error
    fmt.Println(errors.As(err, &target))
}

type MyError struct{}

func (err *MyError) Error() string {
    return "oops!"
}

Running this test returns the build error second argument to errors.As should not be *error.

Go Playground

However, when running the exact same code in main, then the program runs without issues:

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := &MyError{}
    var target error
    fmt.Println(errors.As(err, &target))
}

type MyError struct{}

func (err *MyError) Error() string {
    return "oops!"
}

Go Playground

I am seeing this behavior in the Go Playground and my local development environment, both of which are using Go 1.20.

Is this a bug in Go?

Edit

I can work around the build failure in the test by creating an Error type:

package main

import (
    "errors"
    "fmt"
    "testing"
)

type Error error // <===== Add error type

func TestError(t *testing.T) {
    err := &MyError{}
    var target Error // <===== Use Error type
    fmt.Println(errors.As(err, &target))
}

type MyError struct{}

func (err *MyError) Error() string {
    return "oops!"
}

Solution

  • The error is reported by the go vet command. The go test command automatically runs go vet to report significant problems. The go build command does not run the go vet command.

    The warning is not a bug in Go.

    There's no purpose in calling errors.As with a *error as the second argument because you already know that the first argument satisfies the error interface. You are almost certainly doing something wrong.