-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
errors.go
66 lines (57 loc) · 1.68 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
package models
import (
"strings"
)
// JSONAPIErrors holds errors conforming to the JSONAPI spec.
type JSONAPIErrors struct {
Errors []JSONAPIError `json:"errors"`
}
// JSONAPIError is an individual JSONAPI Error.
type JSONAPIError struct {
Detail string `json:"detail"`
}
// NewJSONAPIErrors creates an instance of JSONAPIErrors, with the intention
// of managing a collection of them.
func NewJSONAPIErrors() *JSONAPIErrors {
fe := JSONAPIErrors{
Errors: []JSONAPIError{},
}
return &fe
}
// NewJSONAPIErrorsWith creates an instance of JSONAPIErrors populated with this
// single detail.
func NewJSONAPIErrorsWith(detail string) *JSONAPIErrors {
fe := NewJSONAPIErrors()
fe.Errors = append(fe.Errors, JSONAPIError{Detail: detail})
return fe
}
// Error collapses the collection of errors into a collection of comma separated
// strings.
func (jae *JSONAPIErrors) Error() string {
var messages []string
for _, e := range jae.Errors {
messages = append(messages, e.Detail)
}
return strings.Join(messages, ",")
}
// Add adds a new error to JSONAPIErrors with the passed detail.
func (jae *JSONAPIErrors) Add(detail string) {
jae.Errors = append(jae.Errors, JSONAPIError{Detail: detail})
}
// Merge combines the arrays of the passed error if it is of type JSONAPIErrors,
// otherwise simply adds a single error with the error string as detail.
func (jae *JSONAPIErrors) Merge(e error) {
switch typed := e.(type) {
case *JSONAPIErrors:
jae.Errors = append(jae.Errors, typed.Errors...)
default:
jae.Add(e.Error())
}
}
// CoerceEmptyToNil will return nil if JSONAPIErrors has no errors.
func (jae *JSONAPIErrors) CoerceEmptyToNil() error {
if len(jae.Errors) == 0 {
return nil
}
return jae
}