-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror.go
More file actions
66 lines (58 loc) · 1.3 KB
/
error.go
File metadata and controls
66 lines (58 loc) · 1.3 KB
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
package schema
import (
"fmt"
"sort"
"strings"
)
// Error is used to record errors that happen during a schema check
type Error struct {
Errors map[string]string
}
// Add adds an error
func (e *Error) Add(field, message string) {
if e.Errors == nil {
e.Errors = map[string]string{}
}
if msg, exists := e.Errors[field]; exists {
message = msg + ", " + message
}
e.Errors[field] = message
}
// Any checks if there are any errors
func (e *Error) Any() bool {
return len(e.Errors) > 0
}
func (e *Error) Error() string {
msgs := []string{}
for field, message := range e.Errors {
if field == selfField {
msgs = append(msgs, message)
} else {
msgs = append(msgs, fmt.Sprintf("%q: %s", field, message))
}
}
sort.Strings(msgs)
return strings.Join(msgs, "\n")
}
// Merge merges another error into this error to have a error tree.
func (e *Error) Merge(otherField string, other *Error) {
for field, msg := range other.Errors {
f := otherField
if field != selfField {
if isErrorIdxField(field) {
f = fmt.Sprintf("%s%s", otherField, field)
} else {
f = fmt.Sprintf("%s.%s", otherField, field)
}
}
e.Add(f, msg)
}
}
// SelfError is an error without any field it describes
func SelfError(msg string) *Error {
return &Error{
Errors: map[string]string{
selfField: msg,
},
}
}