go-validator/validator

use different error type for "internal" errors

bodokaiser opened this issue · 3 comments

Hello Roberto!

Have you thought of using a different error struct for internal errors (e.g. ErrUnsupported, ErrBadParameter, ErrUnknownTag)?

One use case where this may be handy is to decide if I send a http.StatusInternalServerError or a http.StatusBadRequest or maybe even do a panic because of wrong validation settings.

I suggest to change TextError to:

ValidationError - Used when value does not pass validation constraint.

type ValidationError string

func (err ValidationError) Error() string {
    return err
}

func (err ValidationError) MarshalText() ([]byte, error) {
    // ...
}

RuntimeError - Used constraints (tags) or values are wrong.

type RuntimeError string

func (err ValidationError) Error() string {
    return err
}

func (err ValidationError) MarshalText() ([]byte, error) {
    // ...
}

In a http.HandlerFunc we then could do:

func HandlerFunc(w http.ResponseWriter, r *http.Request) {
    // some error from validator
    var err error

    switch t := err.(type) {
    case validator.ValidationError:
        http.Error(w, err.Error(), http.StatusBadRequest)
    case validator.RuntimeError:
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

But @robteix must decide if this is a breaking change or not. I personally would consider it as one as people may do error checks agains ErrUnknownTag or something.

It is breaking but go ahead. Just do a PR to master and I'll release it as
v2. Thanks!

-rst

Sent from my mobile
Please forgive the spelling and brevity.