bufbuild / protovalidate-go

Protocol Buffer Validation for Go
https://pkg.go.dev/github.com/bufbuild/protovalidate-go
Apache License 2.0
294 stars 19 forks source link

The validate returns an error object. How do I get the correct field name and the corresponding check message #105

Closed tocomp closed 9 months ago

tocomp commented 9 months ago
var err error
var pv *protovalidate.Validator
pv, err = protovalidate.New()
if err != nil {
    fmt.Println("failed to initialize validator:", err)
}

if err = pv.Validate(req); err != nil {
    fmt.Println("validation failed:", err)
} else {
    fmt.Println("validation succeeded")
}
validation failed: validation error:
 - versionId: value length must be at least 32 characters [string.min_len]
tocomp commented 9 months ago

Thanks, I found a way to convert ValidationError

sosyz commented 5 months ago

in the package has this comments

// A ValidationError is returned if one or more constraints on a message are
// violated. This error type can be converted into a validate.Violations
// message via ToProto.
//
//    err = validator.Validate(msg)
//    var valErr *ValidationError
//    if ok := errors.As(err, &valErr); ok {
//      pb := valErr.ToProto()
//      // ...
//    }
ValidationError = errors.ValidationError

so I wrote the code based on this comments

if err := v.Validate(pr); err != nil {
    var valErr *protovalidate.ValidationError
    if ok := errors.As(err, &valErr); ok {
        return nil, errors.New(
            400,
            "0",
            valErr.ToProto().GetViolations()[0].GetMessage(), // I not check the err length
        )
    }

    return nil, err
}

It's working! The API returns the error message

{
    "code": 400,
    "reason": "0",
    "message": "xxxxxxxxxxxxxxxxxxxxxxxx",
}

Maybe we should add a check for the error length?