-
Notifications
You must be signed in to change notification settings - Fork 2
/
error_handler.go
84 lines (67 loc) · 1.71 KB
/
error_handler.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
package error_handler
import (
"context"
"github.com/americanas-go/ignite/labstack/echo.v4"
"github.com/americanas-go/log"
e "github.com/labstack/echo/v4"
)
func Register(ctx context.Context, server *echo.Server) error {
o, err := NewOptions()
if err != nil {
return nil
}
h := NewErrorHandlerWithOptions(o)
return h.Register(ctx, server)
}
type ErrorHandler struct {
options *Options
}
func NewErrorHandlerWithOptions(options *Options) *ErrorHandler {
return &ErrorHandler{options: options}
}
func NewErrorHandlerWithConfigPath(path string) (*ErrorHandler, error) {
o, err := NewOptionsWithPath(path)
if err != nil {
return nil, err
}
return NewErrorHandlerWithOptions(o), nil
}
func NewErrorHandler() *ErrorHandler {
o, err := NewOptions()
if err != nil {
log.Fatalf(err.Error())
}
return NewErrorHandlerWithOptions(o)
}
func (i *ErrorHandler) Register(ctx context.Context, server *echo.Server) error {
if !i.options.Enabled {
return nil
}
logger := log.FromContext(ctx)
logger.Trace("configuring error handler in echo")
server.Instance().HTTPErrorHandler = errorHandler(server)
server.Instance().Use(errorConverter)
logger.Debug("error handler successfully configured in echo")
return nil
}
func errorHandler(server *echo.Server) func(err error, c e.Context) {
return func(err error, c e.Context) {
if !c.Response().Committed {
if server.Options().Type != "REST" {
echo.ErrorHandlerString(err, c)
} else {
echo.ErrorHandlerJSON(err, c)
}
}
}
}
func errorConverter(next e.HandlerFunc) e.HandlerFunc {
return func(c e.Context) error {
err := next(c)
if err != nil {
status := echo.ErrorStatusCode(err)
return e.NewHTTPError(status, err.Error())
}
return nil
}
}