package middleware import ( "fmt" "github.com/gin-gonic/gin" "hongze/hongze_google_api/controller/resp" "hongze/hongze_google_api/global" "net/http" "runtime" ) // Recover 异常处理 func Recover() gin.HandlerFunc { return func(c *gin.Context) { contentType := c.ContentType() // 为 multipart forms 设置较低的内存限制(50M) (默认是 32 MiB) if contentType == "multipart/form-data" { err := c.Request.ParseMultipartForm(10 << 20) if err != nil { resp.Custom(http.StatusRequestEntityTooLarge, "上传文件太大,err:"+err.Error(), c) c.Abort() return } } defer func() { if err := recover(); err != nil { stack := "" msg := fmt.Sprintf("The request url is %v", c.Request.RequestURI) stack += msg + "
" global.LOG.Critical(msg) msg = fmt.Sprintf("The request data is %v", c.Params) stack += msg + "
" global.LOG.Critical(msg) msg = fmt.Sprintf("Handler crashed with error %v", err) stack += msg + "
" global.LOG.Critical(msg) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } global.LOG.Critical(fmt.Sprintf("%s:%d", file, line)) stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d
", file, line)) } fmt.Println("stack:", stack) resp.Custom(http.StatusInternalServerError, "系统异常", c) //go alarm_msg.SendAlarmMsg(utils.APPNAME+"崩了"+time.Now().Format(utils.FormatDateTime)+";Err:"+stack, 3) return } }() c.Next() } }