-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_error.go
67 lines (56 loc) · 1.58 KB
/
handler_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
package api
import (
"net/http"
"reflect"
"github.com/labstack/echo/v4"
)
type errorProcessor func(error, echo.Context)
// ErrorHandler is a wrapper on echo.HTTPErrorHandler
type ErrorHandler struct {
Handler echo.HTTPErrorHandler
processors map[string]errorProcessor
}
// NewErrorHandler sets up the mapping of error type to handler
func NewErrorHandler() *ErrorHandler {
eh := ErrorHandler{}
eh.Handler = eh.errorHandlerFunc
eh.processors = make(map[string]errorProcessor)
eh.processors[errorType(&echo.HTTPError{})] = echoHTTPErrorProcessor
return &eh
}
func (eh *ErrorHandler) errorHandlerFunc(err error, c echo.Context) {
p, found := eh.processors[errorType(err)]
if !found {
p = defaultErrorProcessor
}
p(err, c)
}
func echoHTTPErrorProcessor(err error, c echo.Context) {
if he, ok := err.(*echo.HTTPError); ok && clientError(he.Code) {
sendResponse(he.Code, he.Message.(string), c)
return
}
defaultErrorProcessor(err, c)
}
func clientError(statusCode int) bool {
return statusCode < http.StatusInternalServerError && statusCode >= http.StatusBadRequest
}
func defaultErrorProcessor(err error, c echo.Context) {
sendResponse(http.StatusInternalServerError, err.Error(), c)
}
func sendResponse(code int, res interface{}, c echo.Context) {
if !c.Response().Committed {
var err error
if c.Request().Method == http.MethodHead {
err = c.NoContent(code)
} else {
err = c.JSON(code, res)
}
if err != nil {
c.Logger().Errorf("Failed to send error response. Error: %v", err.Error())
}
}
}
func errorType(e error) string {
return reflect.TypeOf(e).String()
}