-
Notifications
You must be signed in to change notification settings - Fork 164
/
helper.go
39 lines (32 loc) · 938 Bytes
/
helper.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
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package validator
import "strings"
// Validator is a general interface that allows a message to be validated.
type Validator interface {
Validate() error
}
func CallValidatorIfExists(candidate interface{}) error {
if validator, ok := candidate.(Validator); ok {
return validator.Validate()
}
return nil
}
type fieldError struct {
fieldStack []string
nestedErr error
}
func (f *fieldError) Error() string {
return "invalid field " + strings.Join(f.fieldStack, ".") + ": " + f.nestedErr.Error()
}
// FieldError wraps a given Validator error providing a message call stack.
func FieldError(fieldName string, err error) error {
if fErr, ok := err.(*fieldError); ok {
fErr.fieldStack = append([]string{fieldName}, fErr.fieldStack...)
return err
}
return &fieldError{
fieldStack: []string{fieldName},
nestedErr: err,
}
}