-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
85 lines (73 loc) · 1.83 KB
/
errors.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
76
77
78
79
80
81
82
83
84
85
package xerrors
import (
"encoding/json"
"strings"
"sync"
)
// Errors holds onto all of the error messages
// that get generated during the validation process.
type Errors struct {
Errors map[string][]string `json:"errors" xml:"errors"`
Lock *sync.RWMutex `json:"-"`
}
// NewErrors returns a pointer to a Errors
// object that has been primed and ready to go.
func NewErrors() *Errors {
return &Errors{
Errors: make(map[string][]string),
Lock: new(sync.RWMutex),
}
}
// Error implements the error interface
func (v *Errors) Error() string {
errs := []string{}
for _, v := range v.Errors {
errs = append(errs, v...)
}
return strings.Join(errs, "\n")
}
// Count returns the number of errors.
func (v *Errors) Count() int {
return len(v.Errors)
}
// HasAny returns true/false depending on whether any errors
// have been tracked.
func (v *Errors) HasAny() bool {
if v == nil {
return false
}
return v.Count() > 0
}
// Append concatenates two Errors objects together.
// This will modify the first object in place.
func (v *Errors) Append(ers *Errors) {
for key, value := range ers.Errors {
for _, msg := range value {
v.Add(key, msg)
}
}
}
// Add will add a new message to the list of errors using
// the given key. If the key already exists the message will
// be appended to the array of the existing messages.
func (v *Errors) Add(key string, msg string) {
v.Lock.Lock()
v.Errors[key] = append(v.Errors[key], msg)
v.Lock.Unlock()
}
// Get returns an array of error messages for the given key.
func (v *Errors) Get(key string) []string {
return v.Errors[key]
}
func (v *Errors) String() string {
b, _ := json.Marshal(v)
return string(b)
}
// Keys return all field names which have error
func (v *Errors) Keys() []string {
keys := []string{}
for key := range v.Errors {
keys = append(keys, key)
}
return keys
}