pointers – How can I store different error interface implementations together and then use them for type comparison in Go?-ThrowExceptions

Exception or error:

I’m trying to write a table test in go where the test cases will result in different errors. I then want to check if the type of the error matches a an error type defined in the test case, using errors.As(). Each test case is defined by a struct, so there needs to be a type in the struct that can hold any implementation of the interface error, which is then also to verify that the correct type was returned in the test.

I have tried defining the struct as follows

type testCase struct {
        testInput string
        expectedError error
}

I also have a number of custom errors that implement the error interface, lets say one is called myCustomError

I then declare a variable of that struct like this:

mTest := testCase{
        testInput: "some failing string",
        expectedError: myCustomError{},
}

if I then do the test like this…

err := someFunc(mTest.testInput)
if errors.As(err, &mTest.expectedError) {
        // test have succeeded
}

… the if statement will always return true, regardless of which of my custom error types is returned.

I made a minimal example if this behavior on the Go Playground here: https://play.golang.org/p/uMdbMvfcdQi

In the playground example, I expect the string “matching myError1” to be printed twice, but instead it also matches myError2 when the value is stored as a plain error before it is used to check the type of the variable err.
Is is even possible to do something like this?

How to solve:

Store a pointer to the target value in the test case.

type testCase struct {
    testInput string
    expectedError interface{}
}

mTest := testCase{
    testInput: "some failing string",
    expectedError: &myCustomError{},
}

err := someFunc(mTest.testInput)
if errors.As(err, mTest.expectedError) {
    // test have succeeded
}

Minimal example: https://play.golang.org/p/igJy9L_ui73

Leave a Reply

Your email address will not be published. Required fields are marked *