Browse Source

export http status code

Paul 6 years ago
parent
commit
e1d9064d95
2 changed files with 32 additions and 12 deletions
  1. 6
    1
      request/error.go
  2. 26
    11
      request/request.go

+ 6
- 1
request/error.go View File

1
 package request
1
 package request
2
 
2
 
3
 type HTTPError struct {
3
 type HTTPError struct {
4
-	Msg string `json:"msg" example:"status bad request"`
4
+	Status int    `json:"status" example:"http status code"`
5
+	Msg    string `json:"msg" example:"status bad request"`
6
+}
7
+
8
+func (e HTTPError) Error() string {
9
+	return e.Msg
5
 }
10
 }

+ 26
- 11
request/request.go View File

3
 import (
3
 import (
4
 	"fmt"
4
 	"fmt"
5
 	"net/http"
5
 	"net/http"
6
-	"runtime"
7
 
6
 
8
 	"github.com/gin-gonic/gin"
7
 	"github.com/gin-gonic/gin"
9
-	"github.com/sirupsen/logrus"
10
 )
8
 )
11
 
9
 
12
 type Checker interface {
10
 type Checker interface {
15
 
13
 
16
 func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
14
 func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
17
 	if r != nil {
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
 			return true
22
 			return true
20
 		}
23
 		}
21
 
24
 
22
 		if checker, ok := r.(Checker); ok {
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
 	for _, f := range fs {
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
 			return true
44
 			return true
30
 		}
45
 		}
31
 	}
46
 	}
33
 	return false
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
 	if err == nil {
52
 	if err == nil {
38
 		return false
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
 	return true
63
 	return true
49
 }
64
 }
50
 
65