|
@@ -3,10 +3,8 @@ package request
|
3
|
3
|
import (
|
4
|
4
|
"fmt"
|
5
|
5
|
"net/http"
|
6
|
|
- "runtime"
|
7
|
6
|
|
8
|
7
|
"github.com/gin-gonic/gin"
|
9
|
|
- "github.com/sirupsen/logrus"
|
10
|
8
|
)
|
11
|
9
|
|
12
|
10
|
type Checker interface {
|
|
@@ -15,17 +13,34 @@ type Checker interface {
|
15
|
13
|
|
16
|
14
|
func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
|
17
|
15
|
if r != nil {
|
18
|
|
- if Fail(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
|
|
16
|
+ err := ctx.ShouldBind(r)
|
|
17
|
+ if err != nil {
|
|
18
|
+ err = HTTPError{Status: http.StatusBadRequest, Msg: err.Error()}
|
|
19
|
+ }
|
|
20
|
+
|
|
21
|
+ if Fail(ctx, err) {
|
19
|
22
|
return true
|
20
|
23
|
}
|
21
|
24
|
|
22
|
25
|
if checker, ok := r.(Checker); ok {
|
23
|
|
- return Fail(ctx, http.StatusBadRequest, checker.Check())
|
|
26
|
+ err := checker.Check()
|
|
27
|
+ if err != nil {
|
|
28
|
+ err = HTTPError{Status: http.StatusBadRequest, Msg: err.Error()}
|
|
29
|
+ }
|
|
30
|
+
|
|
31
|
+ if Fail(ctx, err) {
|
|
32
|
+ return true
|
|
33
|
+ }
|
24
|
34
|
}
|
25
|
35
|
}
|
26
|
36
|
|
27
|
37
|
for _, f := range fs {
|
28
|
|
- if Fail(ctx, http.StatusBadRequest, f()) {
|
|
38
|
+ err := f()
|
|
39
|
+ if err != nil {
|
|
40
|
+ err = HTTPError{Status: http.StatusBadRequest, Msg: err.Error()}
|
|
41
|
+ }
|
|
42
|
+
|
|
43
|
+ if Fail(ctx, err) {
|
29
|
44
|
return true
|
30
|
45
|
}
|
31
|
46
|
}
|
|
@@ -33,18 +48,18 @@ func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
|
33
|
48
|
return false
|
34
|
49
|
}
|
35
|
50
|
|
36
|
|
-func Fail(ctx *gin.Context, status int, err error) bool {
|
|
51
|
+func Fail(ctx *gin.Context, err error) bool {
|
37
|
52
|
if err == nil {
|
38
|
53
|
return false
|
39
|
54
|
}
|
40
|
55
|
|
41
|
|
- ctx.JSON(status, HTTPError{Msg: err.Error()})
|
42
|
|
-
|
43
|
|
- if status == http.StatusInternalServerError {
|
44
|
|
- _, file, line, _ := runtime.Caller(1)
|
45
|
|
- logrus.WithField("err", err).Errorf("file:%s line:%d", file, line)
|
|
56
|
+ status := http.StatusInternalServerError
|
|
57
|
+ if v, ok := err.(HTTPError); ok {
|
|
58
|
+ status = v.Status
|
46
|
59
|
}
|
47
|
60
|
|
|
61
|
+ ctx.JSON(status, gin.H{"msg": err.Error()})
|
|
62
|
+
|
48
|
63
|
return true
|
49
|
64
|
}
|
50
|
65
|
|