recover.go 1.5 KB

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