-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
111 lines (93 loc) · 2.68 KB
/
error.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
101
102
103
104
105
106
107
108
109
110
111
package response
import (
"encoding/json"
"fmt"
"strings"
)
const (
invalidJsonBodyMsg = "invalid json body"
invalidValueFieldJsonMsg = "invalid value for json field"
internalServerErrorMsg = "internal service error"
)
type responseError struct {
Code int `json:"code,omitempty"`
Source string `json:"source,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
Destination string `json:"destination,omitempty"`
Fields []*Field `json:"fields,omitempty"`
}
type Field struct {
Field string `json:"field,omitempty"`
Message string `json:"message,omitempty"`
Location string `json:"location,omitempty"`
}
type responseErrorOptions struct {
Code int `json:"code,omitempty"`
Source string `json:"source,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
Destination string `json:"destination,omitempty"`
Fields []*Field `json:"fields,omitempty"`
}
func newResponseError(options *responseErrorOptions) *responseError {
return &responseError{
Code: options.Code,
Source: options.Source,
Message: options.Message,
Details: options.Details,
Destination: options.Destination,
Fields: options.Fields,
}
}
func jsonError(err error) (*responseError, bool) {
switch t := err.(type) {
case *json.SyntaxError:
return &responseError{
Message: invalidJsonBodyMsg,
}, true
case *json.UnmarshalTypeError:
return &responseError{
Message: invalidValueFieldJsonMsg,
Details: fmt.Sprintf("unexpected value for field '%v'", t.Field),
}, true
}
return nil, false
}
func newValidationErrorFields(err string) []*Field {
var (
res = strings.Split(err, "\",\"")
errs []*Field
)
for _, re := range res {
re = strings.ReplaceAll(re, `"`, "")
msg := strings.Split(strings.TrimSpace(re), ":")
if len(msg) == 2 {
field, location := getFieldNameAndLocation(msg[0])
errs = append(errs, &Field{
Field: field,
Message: strings.TrimSuffix(strings.TrimSpace(msg[1]), "."),
Location: location,
})
}
if len(msg) > 2 {
field, location := getFieldNameAndLocation(msg[0])
errs = append(errs, &Field{
Field: field,
Message: strings.TrimSuffix(strings.TrimSpace(formatMessage(msg[0], err)), "."),
Location: location,
})
}
}
return errs
}
func formatMessage(s string, v string) string {
return strings.ReplaceAll(v, s+":", "")
}
func getFieldNameAndLocation(data string) (string, string) {
res := strings.Split(strings.TrimSpace(data), "@")
if len(res) == 1 {
return data, "body"
}
return strings.TrimSpace(res[0]), strings.TrimSpace(res[1])
}