This repository has been archived by the owner on Dec 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server_errors.go
292 lines (244 loc) · 6.81 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
package catu
import (
"errors"
"fmt"
"net/http"
"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(err error, c echo.Context) {
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
}).Debug("catu.CustomHTTPErrorHandler running")
var ctx *RequestContext
switch v := c.(type) {
case *RequestContext:
ctx = v
default:
ctx = NewRequestContext(&RequestContextOpts{EchoContext: c})
}
code := 0
if he, ok := err.(HTTPErrorInterface); ok {
code = he.GetCode()
if ctx.GetResponseContentType() == "application/json" {
c.JSON(code, he)
return
}
}
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
if ctx.GetResponseContentType() == "application/json" {
c.JSON(code, 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 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": fmt.Sprintf("%+v\n", 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{
"err": fmt.Sprintf("%+v\n", 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("catu.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 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("catu.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("catu.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 {
logrus.WithFields(logrus.Fields{
"err": fmt.Sprintf("%+v\n", err),
"code": "400",
}).Debug("catu.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":
ctx.Title = "Bad request"
if err := ctx.Render(http.StatusInternalServerError, "400", &TemplateCTX{
Ctx: ctx,
}); err != nil {
ctx.Logger().Error(err)
}
return nil
default:
return ctx.JSON(http.StatusBadRequest, 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
}
}