-
Notifications
You must be signed in to change notification settings - Fork 38
/
errors.go
100 lines (82 loc) · 1.84 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package graphql
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"github.com/stateful/runme/internal/client/graphql/query"
)
var ErrNoData = errors.New("no data")
type APIError struct {
apiError error
userErrors []query.UserError
}
func NewAPIError(apiErr error, uErrs ...interface{}) error {
e := APIError{}
e.SetAPIErrors(apiErr)
for _, err := range uErrs {
e.SetUserErrors(convertUserErrors(err))
}
if e.apiError != nil || e.userErrors != nil {
return &e
}
return nil
}
func (e *APIError) SetAPIErrors(err error) {
if err == nil {
return
}
e.apiError = err
}
func (e *APIError) SetUserErrors(val []query.UserError) {
if len(val) == 0 {
return
}
e.userErrors = val
}
func (e *APIError) Unwrap() error {
if e == nil {
return nil
}
return e.apiError
}
func (e *APIError) Error() string {
if e.apiError != nil {
return e.apiError.Error()
}
if len(e.userErrors) > 0 {
var b bytes.Buffer
_, _ = b.WriteString(userErrorString(e.userErrors[0]))
for i := 1; i < len(e.userErrors); i++ {
_ = b.WriteByte('\n')
_, _ = b.WriteString(userErrorString(e.userErrors[i]))
}
return b.String()
}
return ""
}
func userErrorString(err query.UserError) string {
return fmt.Sprintf("error %q affected %s fields", err.GetMessage(), strings.Join(err.GetField(), ", "))
}
func convertUserErrors(uErrs interface{}) (result []query.UserError) {
if uErrs == nil {
return nil
}
userErrorType := reflect.TypeOf((*query.UserError)(nil)).Elem()
if typ := reflect.TypeOf(uErrs); typ.Kind() == reflect.Slice {
s := reflect.ValueOf(uErrs)
for i := 0; i < s.Len(); i++ {
v := s.Index(i)
if v.Type().Kind() != reflect.Ptr {
v = v.Addr()
}
if v.Type().Implements(userErrorType) {
result = append(result, v.Interface().(query.UserError))
}
}
} else {
panic("uErrs is not a slice")
}
return result
}