/
customerror.go
61 lines (57 loc) · 1.03 KB
/
customerror.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
54
55
56
57
58
59
60
61
package middleware
import (
"fmt"
"net/http"
"runtime"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func CustomError(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
if c.IsAborted() {
c.Status(200)
}
switch errStr := err.(type) {
case string:
p := strings.Split(errStr, "#")
if len(p) == 3 && p[0] == "CustomError" {
statusCode, e := strconv.Atoi(p[1])
if e != nil {
break
}
c.Status(statusCode)
fmt.Println(
time.Now().Format("2006-01-02 15:04:05"),
"[ERROR]",
c.Request.Method,
c.Request.URL,
statusCode,
c.Request.RequestURI,
c.ClientIP(),
p[2],
)
c.JSON(http.StatusOK, gin.H{
"code": statusCode,
"msg": p[2],
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": errStr,
})
}
case runtime.Error:
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": errStr.Error(),
})
default:
panic(err)
}
}
}()
c.Next()
}