Bladeren bron

export http status code

Paul 6 jaren geleden
bovenliggende
commit
e1d9064d95
2 gewijzigde bestanden met toevoegingen van 32 en 12 verwijderingen
  1. 6
    1
      request/error.go
  2. 26
    11
      request/request.go

+ 6
- 1
request/error.go Bestand weergeven

@@ -1,5 +1,10 @@
1 1
 package request
2 2
 
3 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 Bestand weergeven

@@ -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