sentry.go 974 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package middleware
  2. import (
  3. "sync"
  4. sentry2 "gitee.com/xuyiping_admin/pkg/sentry"
  5. "gitee.com/xuyiping_admin/pkg/xerr"
  6. "github.com/getsentry/sentry-go"
  7. sentrygin "github.com/getsentry/sentry-go/gin"
  8. "github.com/gin-gonic/gin"
  9. )
  10. var sentryInitOnce sync.Once
  11. // ReportToSentry report error to sentryhub
  12. func ReportToSentry(dsn string, options ...*sentry.ClientOptions) []gin.HandlerFunc {
  13. sentryInitOnce.Do(func() {
  14. sentry2.MustInit(dsn, options...)
  15. })
  16. return []gin.HandlerFunc{
  17. sentrygin.New(sentrygin.Options{Repanic: true}),
  18. CaptureError,
  19. }
  20. }
  21. func CaptureError(c *gin.Context) {
  22. defer func() {
  23. if len(c.Errors) > 0 {
  24. if sentryHub := sentrygin.GetHubFromContext(c); sentryHub != nil {
  25. sentryHub.WithScope(func(scope *sentry.Scope) {
  26. for _, e := range c.Errors {
  27. if _, isCustom := xerr.IsCustomError(e); isCustom {
  28. continue
  29. }
  30. _ = sentryHub.CaptureException(e.Err)
  31. }
  32. })
  33. }
  34. return
  35. }
  36. }()
  37. c.Next()
  38. }