-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
109 lines (88 loc) · 2.26 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
package laravalidate
import (
"encoding/json"
)
type ValidationError struct {
Mode Mode `json:"mode"`
Language []string `json:"language"`
Errors []FieldErrors `json:"errors"`
}
const fallbackErrorMessage = "Validation Error"
func (v *ValidationError) Error() string {
for _, err := range v.Errors {
for _, field := range err.Errors {
return field.Message
}
}
return fallbackErrorMessage
}
func (v *LaravelValidationError) Error() string {
for _, entry := range v.Errors {
for _, message := range entry.Value {
return message
}
}
return fallbackErrorMessage
}
type FieldErrors struct {
Path string `json:"path"`
Errors []FieldValidatorError `json:"errors"`
}
type FieldValidatorError struct {
Rule string `json:"rule"`
Hint string `json:"hint"`
Message string `json:"message"`
}
type LaravelValidationError struct {
Errors LaravelErrorObj `json:"errors"`
Message string `json:"message"`
}
type LaravelErrorObjEntry struct {
Key string
Value []string
}
type LaravelErrorObj []LaravelErrorObjEntry
func (obj LaravelErrorObj) MarshalJSON() ([]byte, error) {
resp := []byte{'{'}
for i, entry := range obj {
if i != 0 {
resp = append(resp, ',')
}
resp = append(resp, '"')
resp = append(resp, []byte(entry.Key)...)
resp = append(resp, '"', ':')
b, err := json.Marshal(entry.Value)
if err != nil {
return nil, err
}
resp = append(resp, b...)
}
resp = append(resp, '}')
return resp, nil
}
// ToLaravelError converts a ValidationError to Laravel like validation error
func (e *ValidationError) ToLaravelError() *LaravelValidationError {
errors := LaravelErrorObj{}
for _, entry := range e.Errors {
path := entry.Path
errorMessages := []string{}
for _, validatorError := range entry.Errors {
errorMessages = append(errorMessages, validatorError.Message)
}
errors = append(errors, LaravelErrorObjEntry{
Key: path,
Value: errorMessages,
})
}
return &LaravelValidationError{
Errors: errors,
Message: "Form contains errors",
}
}
// Prefix prefixes all paths in the error with the given prefix
func (e *ValidationError) Prefix(prefix string) {
for idx, fieldError := range e.Errors {
fieldError.Path = prefix + fieldError.Path
e.Errors[idx] = fieldError
}
}