-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
85 lines (74 loc) · 1.65 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
package server
import (
"fmt"
"net/http"
"github.com/go-playground/validator"
"github.com/labstack/echo"
)
type customErrHandler struct {
e *echo.Echo
}
var validationErrors = map[string]string{
"required": " is required, but was not received",
"min": "'s value or length is less than allowed",
"max": "'s value or length is bigger than allowed",
}
func getVldErrorMsg(s string) string {
if v, ok := validationErrors[s]; ok {
return v
}
return " failed on " + s + " validation"
}
type resp struct {
Message string `json:"message"`
}
func (ce *customErrHandler) handler(err error, c echo.Context) {
var (
code = http.StatusInternalServerError
msg interface{}
)
type resp struct {
Message interface{} `json:"message"`
}
if ce.e.Debug {
msg = err.Error()
switch err.(type) {
case *echo.HTTPError:
code = err.(*echo.HTTPError).Code
case validator.ValidationErrors:
code = http.StatusBadRequest
}
} else {
switch e := err.(type) {
case *echo.HTTPError:
code = e.Code
msg = e.Message
if e.Internal != nil {
msg = fmt.Sprintf("%v, %v", err, e.Internal)
}
case validator.ValidationErrors:
var errMsg []string
for _, v := range e {
errMsg = append(errMsg, fmt.Sprintf("%s%s", v.Field(), getVldErrorMsg(v.ActualTag())))
}
msg = resp{Message: errMsg}
code = http.StatusBadRequest
default:
msg = http.StatusText(code)
}
if _, ok := msg.(string); ok {
msg = resp{Message: msg}
}
}
// Send response
if !c.Response().Committed {
if c.Request().Method == "HEAD" {
err = c.NoContent(code)
} else {
err = c.JSON(code, msg)
}
if err != nil {
ce.e.Logger.Error(err)
}
}
}