recover.go 1.6 KB

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