recover.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "hongze/hongze_google_api/controller/resp"
  6. "hongze/hongze_google_api/global"
  7. "net/http"
  8. "runtime"
  9. )
  10. // Recover 异常处理
  11. func Recover() gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. contentType := c.ContentType()
  14. // 为 multipart forms 设置较低的内存限制(50M) (默认是 32 MiB)
  15. if contentType == "multipart/form-data" {
  16. err := c.Request.ParseMultipartForm(10 << 20)
  17. if err != nil {
  18. resp.Custom(http.StatusRequestEntityTooLarge, "上传文件太大,err:"+err.Error(), c)
  19. c.Abort()
  20. return
  21. }
  22. }
  23. defer func() {
  24. if err := recover(); err != nil {
  25. stack := ""
  26. msg := fmt.Sprintf("The request url is %v", c.Request.RequestURI)
  27. stack += msg + "</br>"
  28. global.LOG.Critical(msg)
  29. msg = fmt.Sprintf("The request data is %v", c.Params)
  30. stack += msg + "</br>"
  31. global.LOG.Critical(msg)
  32. msg = fmt.Sprintf("Handler crashed with error %v", err)
  33. stack += msg + "</br>"
  34. global.LOG.Critical(msg)
  35. for i := 1; ; i++ {
  36. _, file, line, ok := runtime.Caller(i)
  37. if !ok {
  38. break
  39. }
  40. global.LOG.Critical(fmt.Sprintf("%s:%d", file, line))
  41. stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d</br>", file, line))
  42. }
  43. fmt.Println("stack:", stack)
  44. resp.Custom(http.StatusInternalServerError, "系统异常", c)
  45. //go alarm_msg.SendAlarmMsg(utils.APPNAME+"崩了"+time.Now().Format(utils.FormatDateTime)+";Err:"+stack, 3)
  46. return
  47. }
  48. }()
  49. c.Next()
  50. }
  51. }