-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconstraint.go
53 lines (44 loc) · 1.18 KB
/
constraint.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
// Package changeset used to cast and validate data before saving it to the database.
package changeset
import (
"strings"
"github.com/go-rel/rel"
)
// Constraint defines information to infer constraint error.
type Constraint struct {
Field string
Message string
Code int
Name string
Exact bool
Type rel.ConstraintType
}
// Constraints is slice of Constraint
type Constraints []Constraint
// GetError converts error based on constraints.
// If the original error is constraint error, and it's defined in the constraint list, then it'll be updated with constraint's message.
// If the original error is constraint error but not defined in the constraint list, it'll be converted to unexpected error.
// else it'll not modify the error.
func (constraints Constraints) GetError(err error) error {
cerr, ok := err.(rel.ConstraintError)
if !ok {
return err
}
for _, c := range constraints {
if c.Type == cerr.Type {
if c.Exact && c.Name != cerr.Key {
continue
}
if !c.Exact && !strings.Contains(cerr.Key, c.Name) {
continue
}
return Error{
Message: c.Message,
Field: c.Field,
Code: c.Code,
Err: err,
}
}
}
return err
}