recover.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "hongze/hongze_yb/controller/response"
  6. "hongze/hongze_yb/global"
  7. "hongze/hongze_yb/services/alarm_msg"
  8. "hongze/hongze_yb/utils"
  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. response.Custom(http.StatusRequestEntityTooLarge, "上传文件太大,err:"+err.Error(), c)
  22. c.Abort()
  23. return
  24. }
  25. }
  26. defer func() {
  27. if err := recover(); err != 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. response.Custom(http.StatusInternalServerError, "系统异常", c)
  48. //c.JSON(http.StatusInternalServerError, Err)
  49. //go services.SendEmail(utils.APPNAME+"崩了"+time.Now().Format("2006-01-02 15:04:05"), stack, utils.EmailSendToUsers)
  50. go alarm_msg.SendAlarmMsg(utils.APPNAME+"崩了"+time.Now().Format("2006-01-02 15:04:05")+";Err:"+stack, 3)
  51. return
  52. }
  53. }()
  54. c.Next()
  55. }
  56. }