lundi 2 mars 2020

In Go, how to check that a return value of a function satisfies the error interface?

I'd like to write some code which inspects the methods of a struct and makes certain assertions on them, for example, that the last thing returned by them should be an error. I've tried the following example script:

import (
    "context"
    "reflect"
)

type Service struct {
    name string
}

func (svc *Service) Handle(ctx context.Context) (string, error) {
    return svc.name, nil
}

func main() {
    s := &Service{}
    t := reflect.TypeOf(s)

    for i := 0; i < t.NumMethod(); i++ {
        f := t.Method(i).Func.Type()

        f.Out(f.NumOut() - 1).Implements(reflect.TypeOf(error))
    }
}

However, this yields a

./main.go:23:51: type error is not an expression

What does compile are instead the following two lines at the end:

    var err error
    f.Out(f.NumOut() - 1).Implements(reflect.TypeOf(err))

However, this yields a panic:

panic: reflect: nil type passed to Type.Implements

What would be the correct way to check that the last arguments implements the error interface? In other words, how do I get a reflect.Type of an error interface?





Aucun commentaire:

Enregistrer un commentaire