-
Notifications
You must be signed in to change notification settings - Fork 41
/
api-errors.go
48 lines (41 loc) · 884 Bytes
/
api-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
package tools
import (
"github.com/gin-gonic/gin"
"net/http"
)
type RequestError struct {
Status int
CustomMessage string
Err error
}
func (r RequestError) Error() string {
if r.Err != nil {
return r.Err.Error()
} else {
return ""
}
}
func (r RequestError) ToResponse() gin.H {
res := gin.H{"status": r.Status, "message": r.CustomMessage}
if r.Err != nil {
res["error"] = r.Error()
}
return res
}
func ErrorHandler(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
err := c.Errors[0]
switch err.Err.(type) {
case RequestError:
e := err.Err.(RequestError)
c.Errors = []*gin.Error{} // clear errors so they don't get logged
c.JSON(e.Status, e.ToResponse())
default:
c.Errors = []*gin.Error{} // clear errors so they don't get logged
c.JSON(http.StatusInternalServerError, err.Err.Error())
}
c.Abort()
return
}
}