-
Notifications
You must be signed in to change notification settings - Fork 3
/
validation.go
75 lines (64 loc) · 1.89 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package grpctools
import (
"fmt"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// VErrors contains a set of field-violations.
type VErrors []*errdetails.BadRequest_FieldViolation
// VErrorsConvert extracts validation errors from an error.
// This function will return nil if no validation errors are attached.
func VErrorsConvert(err error) VErrors {
return VErrorsFromStatus(status.Convert(err))
}
// VErrorsFromStatus extracts validation errors from status.
func VErrorsFromStatus(sts *status.Status) VErrors {
for _, detail := range sts.Details() {
switch t := detail.(type) {
case *errdetails.BadRequest:
return t.GetFieldViolations()
}
}
return nil
}
// Append appends a field message.
func (e VErrors) Append(field, message string) VErrors {
return append(e, &errdetails.BadRequest_FieldViolation{
Field: field,
Description: message,
})
}
// Len returns the error count.
func (e VErrors) Len() int {
return len(e)
}
// Reset resets the slice.
func (e VErrors) Reset() VErrors {
return e[:0]
}
// Messages returns messages.
func (e VErrors) Messages() []string {
msgs := make([]string, 0, e.Len())
for _, fv := range e {
msgs = append(msgs, fv.Field+": "+fv.Description)
}
return msgs
}
// Status returns a custom status.
func (e VErrors) Status(code codes.Code, message string) *status.Status {
// this should not error, if it does it's better panic here to instantly figure out why
sts, err := status.New(code, message).
WithDetails(&errdetails.BadRequest{FieldViolations: e})
if err != nil {
panic(fmt.Sprintf("Unexpected error attaching metadata: %v", err))
}
return sts
}
// InvalidArgument returns an InvalidArgument status.
func (e VErrors) InvalidArgument(message string) *status.Status {
if message == "" {
message = "invalid argument"
}
return e.Status(codes.InvalidArgument, message)
}