-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy patherror.go
102 lines (87 loc) · 2.32 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
package httpserver
import (
"net/http"
"github.com/ankorstore/yokai/log"
"github.com/go-errors/errors"
"github.com/labstack/echo/v4"
)
// JsonErrorHandler provides a [echo.HTTPErrorHandler] that outputs errors in JSON format.
// It can also be configured to obfuscate error message (to avoid to leak sensitive details), and to add the error stack to the response.
type JsonErrorHandler struct {
obfuscate bool
stack bool
}
// NewJsonErrorHandler returns a new JsonErrorHandler instance.
func NewJsonErrorHandler(obfuscate bool, stack bool) *JsonErrorHandler {
return &JsonErrorHandler{
obfuscate: obfuscate,
stack: stack,
}
}
// Handle handles errors.
func (h *JsonErrorHandler) Handle() echo.HTTPErrorHandler {
return func(err error, c echo.Context) {
logger := log.CtxLogger(c.Request().Context())
if c.Response().Committed {
return
}
var httpError *echo.HTTPError
if errors.As(err, &httpError) {
if httpError.Internal != nil {
var internalHttpError *echo.HTTPError
if errors.As(httpError.Internal, &internalHttpError) {
httpError = internalHttpError
}
}
} else {
httpError = &echo.HTTPError{
Code: http.StatusInternalServerError,
Message: err.Error(),
}
}
var logRespFields map[string]interface{}
if h.stack {
errStack := "n/a"
if err != nil {
errStack = errors.New(err).ErrorStack()
}
switch m := httpError.Message.(type) {
case error:
logRespFields = map[string]interface{}{
"message": m.Error(),
"stack": errStack,
}
default:
logRespFields = map[string]interface{}{
"message": m,
"stack": errStack,
}
}
} else {
switch m := httpError.Message.(type) {
case error:
logRespFields = map[string]interface{}{
"message": m.Error(),
}
default:
logRespFields = map[string]interface{}{
"message": m,
}
}
}
logger.Error().Err(err).Fields(logRespFields).Msg("error handler")
httpRespFields := logRespFields
if h.obfuscate {
httpRespFields["message"] = http.StatusText(httpError.Code)
}
var httpRespErr error
if c.Request().Method == http.MethodHead {
httpRespErr = c.NoContent(httpError.Code)
} else {
httpRespErr = c.JSON(httpError.Code, httpRespFields)
}
if httpRespErr != nil {
logger.Error().Err(httpRespErr).Msg("error handler failure")
}
}
}