github.com/jtzjtz/kit@v1.0.2/middleware/recover_catch/recover_catch.go (about)

     1  package recover_catch
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/gin-gonic/gin"
     6  	"github.com/jtzjtz/kit/log"
     7  	"runtime/debug"
     8  	"time"
     9  )
    10  
    11  type result struct {
    12  	Code    int         `json:"code"`
    13  	Message string      `json:"message"`
    14  	Data    interface{} `json:"data"`
    15  }
    16  
    17  func RecoverCatchMiddleware(env, appName string) gin.HandlerFunc {
    18  	return func(c *gin.Context) {
    19  		defer func() {
    20  			if err := recover(); err != nil {
    21  				subject := fmt.Sprintf("【Error】项目:%s 环境:[%s] 异常捕获!", appName, env)
    22  				reqUrl := c.Request.Method + "  " + c.Request.Host + c.Request.RequestURI
    23  				reqUrl += " 请求body:" + getReqBody(c)
    24  				bodyData := fmt.Sprintf("errmsg:%s logtime:%s url:%s useragent:%s clientip:%s debugStack:%s", err, time.Now().Format("2006/01/02 15:04:05.000"), reqUrl, c.Request.UserAgent(), c.GetHeader("X-Real-Ip"), string(debug.Stack()))
    25  				errorData := log.ErrEntity{
    26  					Msg:  subject,
    27  					Data: bodyData,
    28  					Env:  env,
    29  				}
    30  				log.LogError(errorData, c)
    31  				c.Abort()
    32  			}
    33  		}()
    34  		c.Next()
    35  	}
    36  }
    37  
    38  //获取请求body
    39  func getReqBody(ctx *gin.Context) string {
    40  	requestBody := ""
    41  	if ctx.Request.Method == "POST" {
    42  		requestBodyByte, err := ctx.GetRawData()
    43  		if err == nil {
    44  			requestBody = string(requestBodyByte)
    45  		}
    46  	}
    47  	return requestBody
    48  }