polyfloyd / go-errorlint

A source code linter that can be used to find code that will cause problems with Go's error wrapping scheme
MIT License
249 stars 19 forks source link

Ability to toggle assertion linter for interfaces #28

Closed dopey closed 2 years ago

dopey commented 2 years ago

errors can have interfaces - e.g., StackTracer, Logger, Renderable, etc.

In order to check if an error implements an interface (to check if, for example, we can call e.StackTrace()) we do a type assertion. There isn't an easy way to change this to use errors.As because we can't marshal the error into an interface.

I would be nice to be able to turn off errors about type assertion against interfaces.

polyfloyd commented 2 years ago

Hi,

Actually, you can use errors.As with interfaces. Consider the following example:

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := geterr()

    var thing interface {
        Foo()
    }
    if errors.As(err, &thing) {
        thing.Foo()
    }
    fmt.Println(err)
}

func geterr() error {
    return fmt.Errorf("geterr: %w", Fooer{})
}

type Fooer struct{}

func (Fooer) Error() string {
    return "fooer"
}

func (Fooer) Foo() {
    fmt.Println("foo")
}

This will print:

foo
geterr: fooer
dopey commented 2 years ago

This is great! Thanks for the response.