forked from go-catupiry/catu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_errors.go
352 lines (295 loc) · 8.12 KB
/
server_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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package bolo
import (
"errors"
"fmt"
"net/http"
"strconv"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type HTTPErrorInterface interface {
Error() string
GetCode() int
SetCode(code int) error
GetMessage() interface{}
SetMessage(message interface{}) error
}
// HTTPError implements HTTP Error interface, default error object
type HTTPError struct {
Code int `json:"code"`
Message interface{} `json:"message"`
Internal error `json:"-"` // Stores the error returned by an external dependency
}
// Error makes it compatible with `error` interface.
func (e *HTTPError) Error() string {
if e.Internal == nil {
return fmt.Sprintf("code=%d, message=%v", e.Code, e.Message)
}
return fmt.Sprintf("code=%d, message=%v, internal=%v", e.Code, e.Message, e.Internal)
}
func (e *HTTPError) GetCode() int {
return e.Code
}
func (e *HTTPError) SetCode(code int) error {
e.Code = code
return nil
}
func (e *HTTPError) GetMessage() interface{} {
return e.Message
}
func (e *HTTPError) SetMessage(message interface{}) error {
e.Message = message
return nil
}
func (e *HTTPError) GetInternal() error {
return e.Internal
}
func (e *HTTPError) SetInternal(internal error) error {
e.Internal = internal
return nil
}
type ValidationResponse struct {
Errors []*ValidationFieldError `json:"errors"`
}
type ValidationFieldError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Value string `json:"value"`
Message string `json:"message"`
}
func CustomHTTPErrorHandler(app App) func(err error, c echo.Context) {
return func(err error, c echo.Context) {
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
}).Debug("bolo.CustomHTTPErrorHandler running")
var ctx *RequestContext
switch v := c.(type) {
case *RequestContext:
ctx = v
default:
ctx = NewRequestContext(&RequestContextOpts{App: app, EchoContext: c})
}
app.GetEvents().Trigger("http-error", map[string]any{
"error": err,
"echoContext": c,
})
code := 0
if he, ok := err.(HTTPErrorInterface); ok {
code = he.GetCode()
if ctx.GetResponseContentType() == "application/json" {
c.JSON(code, ParseHTTPErrorToResponse(ctx, he))
return
}
} else {
switch c.Get("status").(type) {
case string:
code, _ = strconv.Atoi(c.Get("status").(string))
}
}
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
if ctx.GetResponseContentType() == "application/json" {
c.JSON(code, ParseEchoHTTPErrorToResponse(ctx, he))
return
}
}
if ve, ok := err.(validator.ValidationErrors); ok {
validationError(ve, err, ctx)
return
}
if code == 0 && err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
code = 404
}
switch code {
case 400, 422:
badRequestErrorHandler(err, ctx)
case 401:
unAuthorizedErrorHandler(err, ctx)
case 403:
forbiddenErrorHandler(err, ctx)
case 404:
notFoundErrorHandler(err, ctx)
case 500:
internalServerErrorHandler(err, ctx)
default:
logrus.WithFields(logrus.Fields{
"error": err,
"statusCode": code,
"path": c.Path(),
"method": c.Request().Method,
"AuthenticatedUser": ctx.AuthenticatedUser,
"roles": ctx.GetAuthenticatedRoles(),
}).Warn("customHTTPErrorHandler unknown error status code")
c.JSON(http.StatusInternalServerError, &HTTPError{Code: 500, Message: "Unknown Error"})
}
}
}
func forbiddenErrorHandler(err error, c echo.Context) error {
ctx := c.(*RequestContext)
logParams := logrus.Fields{
"error": err,
"code": "403",
"path": c.Path(),
"method": c.Request().Method,
"roles": ctx.GetAuthenticatedRoles(),
}
if ctx.IsAuthenticated {
if ctx.AuthenticatedUser != nil {
logParams["AuthenticatedUserID"] = ctx.AuthenticatedUser.GetID()
}
}
logrus.WithFields(logParams).Debug("bolo.forbiddenErrorHandler running")
switch ctx.GetResponseContentType() {
case "text/html":
ctx.Title = "Acesso restrito"
if err := c.Render(http.StatusForbidden, "403", &TemplateCTX{
Ctx: ctx,
}); err != nil {
c.Logger().Error(err)
}
return nil
default:
c.JSON(http.StatusForbidden, err)
return nil
}
}
func badRequestErrorHandler(err error, ctx *RequestContext) error {
status := http.StatusBadRequest
if ctx.Get("status") != nil {
status = ctx.Get("status").(int)
}
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": status,
}).Debug("bolo.badRequestErrorHandler running")
switch ctx.GetResponseContentType() {
case "text/html":
ctx.Title = "Bad request"
template := "400"
if ctx.Get("template") != nil {
template = ctx.Get("template").(string)
}
if err := ctx.Render(status, template, &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
ctx.JSON(http.StatusBadRequest, err)
return nil
}
}
func unAuthorizedErrorHandler(err error, ctx *RequestContext) error {
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": "401",
"path": ctx.Path(),
"method": ctx.Request().Method,
"AuthenticatedUser": ctx.AuthenticatedUser,
"roles": ctx.GetAuthenticatedRoles(),
}).Info("bolo.unAuthorizedErrorHandler running")
switch ctx.GetResponseContentType() {
case "text/html":
ctx.Title = "Forbidden"
if err := ctx.Render(http.StatusUnauthorized, "401", &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
ctx.JSON(http.StatusUnauthorized, err)
return nil
}
}
func notFoundErrorHandler(err error, ctx *RequestContext) error {
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": "404",
}).Debug("bolo.notFoundErrorHandler running")
switch ctx.GetResponseContentType() {
case "text/html":
ctx.Title = "Não encontrado"
if err := ctx.Render(http.StatusNotFound, "404", &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
ctx.JSON(http.StatusNotFound, &HTTPError{Code: http.StatusNotFound, Message: "Not Found"})
return nil
}
}
func validationError(ve validator.ValidationErrors, err error, ctx *RequestContext) error {
status := http.StatusUnprocessableEntity
if ctx.Get("status") != nil {
status = ctx.Get("status").(int)
}
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": status,
}).Debug("bolo.validationError running")
resp := ValidationResponse{}
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
var el ValidationFieldError
el.Field = err.Field()
el.Tag = err.Tag()
el.Value = err.Param()
el.Message = err.Error()
resp.Errors = append(resp.Errors, &el)
}
}
switch ctx.GetResponseContentType() {
case "text/html":
if ctx.Title != "" {
ctx.Title = "Bad request"
}
template := "400"
if ctx.Get("template") != nil {
template = ctx.Get("template").(string)
}
if err := ctx.Render(status, template, &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
return ctx.JSON(status, resp)
}
}
func internalServerErrorHandler(err error, ctx *RequestContext) error {
code := http.StatusInternalServerError
if he, ok := err.(*HTTPError); ok {
code = he.Code
}
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": code,
"path": ctx.Path(),
"method": ctx.Request().Method,
"AuthenticatedUser": ctx.AuthenticatedUser,
"roles": ctx.GetAuthenticatedRoles(),
}).Warn("internalServerErrorHandler error")
switch ctx.GetResponseContentType() {
case "text/html":
ctx.Title = "Internal server error"
if err := ctx.Render(http.StatusInternalServerError, "500", &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
if he, ok := err.(*HTTPError); ok {
return ctx.JSON(he.Code, &HTTPError{Code: he.Code, Message: he.Message})
}
ctx.JSON(http.StatusInternalServerError, &HTTPError{Code: http.StatusInternalServerError, Message: "Internal Server Error"})
return nil
}
}