hy c
hy c

Reputation: 115

Why I cannot use Error() for type validator.FieldError

I am using go validator and everything is fine. I can use print everything from err but cannot use Error() or convert the err to string. Does anyone can help me with this?

It shows

err.Error undefined (type validator.FieldError has no field or method Error)

My code:

err = validate.Struct(myData)

if err != nil {

    for _, err := range err.(validator.ValidationErrors) {
        fmt.Println(err)
        fmt.Println(err.Namespace())
        fmt.Println(err.Field())
        fmt.Println(err.StructNamespace())
        fmt.Println(err.StructField())
        fmt.Println(err.Tag())
        fmt.Println(err.ActualTag())
        fmt.Println(err.Kind())
        fmt.Println(err.Type())
        err.Error()

    }

    return
}

Is there any way to use the interface Error()? Or convert the err to string?

Upvotes: 2

Views: 1801

Answers (1)

icza
icza

Reputation: 417592

Your "outer" err is an error (which is returned by validate.Struct()), it has an Error() method.

But the err loop variable is not. You type assert validator.ValidationErrors from the "outer" err, which is:

type ValidationErrors []FieldError

Where FieldError is an interface type but it has no Error() method.

You may call and print the error string of the "outer" err variable, before or after (but not inside) the loop.

if err != nil {
    fmt.Println(err.Error())
    for _, err := range err.(validator.ValidationErrors) {
        // ...
    }
}

To avoid such confusion, use a different name for the loop variable, especially since it's not of type error. fieldErr or simply fe (as in field error) would be a good name.

Upvotes: 3

Related Questions