-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
227 lines (201 loc) · 6.12 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package server
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
)
const (
// InternalErrorType type of common errors
InternalErrorType = "INTERNAL"
// GenericErrorType type of common errors
GenericErrorType = "GENERIC"
// ValidationErrorType type of common errors
ValidationErrorType = "VALIDATION"
)
// ErrorResponse represents the error response
// swagger:model
type ErrorResponse struct {
Error *HTTPError `json:"error"`
}
// HTTPError represents an error that occurred while handling a request
type HTTPError struct {
Code int `json:"code"`
Type string `json:"type"`
Message string `json:"message"`
Internal error `json:"-"`
}
// NewHTTPError creates a new HTTPError instance
func NewHTTPError(code int, etype string, message ...string) *HTTPError {
he := &HTTPError{Code: code, Type: etype}
if len(message) > 0 {
he.Message = message[0]
} else {
he.Message = http.StatusText(code)
}
return he
}
// NewHTTPInternalError creates a new HTTPError instance for internal error
func NewHTTPInternalError(message string) *HTTPError {
return &HTTPError{Code: http.StatusInternalServerError, Type: InternalErrorType, Message: message}
}
// NewHTTPGenericError creates a new HTTPError instance for generic error
func NewHTTPGenericError(message string) *HTTPError {
return &HTTPError{Code: http.StatusBadRequest, Type: GenericErrorType, Message: message}
}
// NewHTTPValidationError creates a new HTTPError instance for validation error
func NewHTTPValidationError(message string) *HTTPError {
return &HTTPError{Code: http.StatusBadRequest, Type: ValidationErrorType, Message: message}
}
// Error makes it compatible with `error` interface
func (he *HTTPError) Error() string {
err := strings.Builder{}
switch {
case he.Internal != nil:
err.WriteString(fmt.Sprintf("code=%d, type=%s, message=%s, internal=%v", he.Code, he.Type, he.Message, he.Internal))
default:
err.WriteString(fmt.Sprintf("code=%d, type=%s, message=%s", he.Code, he.Type, he.Message))
}
return err.String()
}
// SetInternal sets actual internal error for more details
func (he *HTTPError) SetInternal(err error) *HTTPError {
he.Internal = err
return he
}
// MarshalJSON modification
func (he *HTTPError) MarshalJSON() ([]byte, error) {
type alias HTTPError
type custom struct {
*alias
Internal string `json:"internal,omitempty"`
}
output := custom{alias: (*alias)(he)}
if he.Internal != nil {
output.Internal = he.Internal.Error()
}
return json.Marshal(output)
}
// ErrorHandler represents the custom http error handler
type ErrorHandler struct {
e *echo.Echo
}
// NewErrorHandler returns the ErrorHandler instance
func NewErrorHandler(e *echo.Echo) *ErrorHandler {
return &ErrorHandler{e}
}
// Handle is a centralized HTTP error handler.
func (ce *ErrorHandler) Handle(err error, c echo.Context) {
httpErr := NewHTTPError(http.StatusInternalServerError, InternalErrorType)
switch e := err.(type) {
case *HTTPError:
if e.Code != 0 {
httpErr.Code = e.Code
}
if e.Type != "" {
httpErr.Type = e.Type
} else {
httpErr.Type = GenericErrorType
}
if e.Message != "" {
httpErr.Message = e.Message
}
if e.Internal != nil {
ce.e.Logger.Errorf("internal err: %+v", e.Internal)
// httpErr.Internal = e.Internal
}
case *echo.HTTPError:
httpErr.Code = e.Code
httpErr.Type = GenericErrorType
switch em := e.Message.(type) {
case string:
httpErr.Message = em
case []string:
httpErr.Message = strings.Join(em, "\n")
case map[string]interface{}:
if jsonStr, err := json.Marshal(em); err == nil {
httpErr.Message = string(jsonStr)
}
default:
httpErr.Message = fmt.Sprintf("%+v", em)
}
if e.Internal != nil {
ce.e.Logger.Errorf("internal err: %+v", e.Internal)
// httpErr.Internal = e.Internal
}
case validator.ValidationErrors:
httpErr.Code = http.StatusBadRequest
httpErr.Type = ValidationErrorType
var errMsg []string
for _, v := range e {
errMsg = append(errMsg, getVldErrorMsg(v))
}
httpErr.Message = strings.Join(errMsg, "\n")
default:
if ce.e.Debug {
httpErr.Message = err.Error()
}
}
// Send response
if !c.Response().Committed {
if c.Request().Method == http.MethodHead {
err = c.NoContent(httpErr.Code)
} else {
if !ce.e.Debug && httpErr.Code == http.StatusInternalServerError {
ce.e.Logger.Error(httpErr)
httpErr.Message = http.StatusText(httpErr.Code)
httpErr.Internal = nil
httpErr.Type = GenericErrorType
}
err = c.JSON(httpErr.Code, ErrorResponse{Error: httpErr})
}
if err != nil {
ce.e.Logger.Error(err)
}
}
}
var validationErrors = map[string]string{
"required": " is required, but was not received",
"min": "'s value or length is less than allowed",
"max": "'s value or length is bigger than allowed",
"date": " should be a valid date in form of YYYY-MM-DD",
"email": " is an invalid email address",
"phone": " is an invalid phone number",
"url": " is an invalid URL",
"coordinate": " is an invalid latitude, longitude coordinate",
}
func getVldErrorMsg(v validator.FieldError) string {
field := v.Field()
vtag := v.ActualTag()
vtagVal := v.Param()
if msg, ok := validationErrors[vtag]; ok {
return field + msg
}
switch vtag {
case "min":
return field + " minimum allowed length is " + vtagVal
case "max":
return field + " exceeds the maximum allowed length (" + vtagVal + ")"
case "lte":
return field + "'s length should be less than or equal to " + vtagVal
case "lt":
return field + "'s length should be less than " + vtagVal
case "gte":
return field + "'s length should be greater than or equal to " + vtagVal
case "gt":
return field + "'s length should be greater than " + vtagVal
case "oneof":
return field + " should be one of " + strings.Replace(vtagVal, " ", ", ", -1)
case "ltfield":
return field + " should be less than " + vtagVal
case "gtfield":
return field + " should be greater than " + vtagVal
case "eqfield":
return field + " does not match " + vtagVal
case "datetime":
return field + "'s format should be: " + vtagVal
}
return field + " failed on " + vtag + " validation"
}