-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin_handler.go
53 lines (41 loc) · 1.01 KB
/
gin_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
package sfutils
import (
"fmt"
"net/http"
"reflect"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
)
type GinHandlerWithError func(c *gin.Context) error
type GinErrorHandler struct {
errorTypes []reflect.Type
}
func (g *GinErrorHandler) ourErrorType(i interface{}) bool {
errorType := reflect.TypeOf(i)
for _, t := range g.errorTypes {
fmt.Println("errorType:", errorType, t)
if errorType == t {
return true
}
}
return false
}
func (g *GinErrorHandler) RegisterErrorType(i interface{}) {
errorType := reflect.TypeOf(i)
g.errorTypes = append(g.errorTypes, errorType)
}
func (g *GinErrorHandler) S(f GinHandlerWithError) gin.HandlerFunc {
return func(c *gin.Context) {
if err := f(c); err != nil {
if g.ourErrorType(err) {
c.JSON(http.StatusOK, gin.H{"error": err})
} else {
logrus.Errorf("WWW [%s] error: %s\n", c.FullPath(), err.Error())
c.JSON(http.StatusInternalServerError, gin.H{})
}
}
}
}
func NewGinErrorHandler() *GinErrorHandler {
return &GinErrorHandler{}
}