-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors.go
92 lines (81 loc) · 2.38 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
package form_validator
import "fmt"
const (
ERROR_MISSING_VALUE = "ERROR_MISSING_VALUE"
ERROR_INCORRECT_TYPE = "ERROR_INCORRECT_TYPE"
ERROR_FILE_TYPE = "ERROR_FILE_TYPE"
ERROR_FIELDS_DO_NOT_MATCH = "ERROR_FIELDS_DO_NOT_MATCH"
)
type FieldError struct {
Name string
Error Error
}
// FormErrors type enables the caller to access all the form errors
// from a map indexed by name.
type FormErrors map[string]map[string]string
func missingValueError(name string) string {
return fmt.Sprintf("Missing value for %s field", name)
}
func incorrectTypeError(fieldType, name string) string {
return fmt.Sprintf("Expected a value of type %s for %s field", fieldType, name)
}
func fileError(err error) string {
return fmt.Sprintf("File error: %e", err)
}
func fieldsDoNotMatch(field, matchedField string) string {
return fmt.Sprintf("Fields %s and %s should match.", field, matchedField)
}
func setErrorMessage(f *Field, fileErr error) {
switch f.Error.Type {
case ERROR_MISSING_VALUE:
f.Error.Message = missingValueError(f.Name)
break
case ERROR_INCORRECT_TYPE:
f.Error.Message = incorrectTypeError(f.Type, f.Name)
break
case ERROR_FILE_TYPE:
f.Error.Message = fileError(fileErr)
case ERROR_FIELDS_DO_NOT_MATCH:
f.Error.Message = fieldsDoNotMatch(f.Name, f.Matches)
default:
// pass
}
}
// GetFormError access a single form error value
//
// name := GetFormError("name", &c)
func GetFormError(name string, c *Config) Error {
var err Error
for _, v := range c.Fields {
if v.Name == name {
err = v.Error
}
}
return err
}
// GetFormErrors access all form errors as a map (`FormErrors`) indexed off the form names
//
// var formErrs = form_validator.FormErrors{}
// form_validator.GetFormErrors(&c, &formErrs)
//
// If the results of `formErrs` are passed to the template as data then
// all form errors can be accessed from the map via index name, for example:
//
// {{ if .FormErrors.title }}
// <div class="alert alert-danger" role="alert">
// {{ .FormErrors.title.error }}
// </div>
// {{ end }}
//
// In this case `FormErrors.title.error` will produce an error message that
// can be safely displayed to the user.
func GetFormErrors(c *Config, fe *FormErrors) {
for _, v := range c.Fields {
if v.Error.Type != "" {
(*fe)[v.Name] = map[string]string{
v.Name: v.Name,
"error": v.Error.Message,
}
}
}
}