sentry.go 951 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package middleware
  2. import (
  3. sentry2 "kpt-tmr-group/pkg/sentry"
  4. "kpt-tmr-group/pkg/xerr"
  5. "sync"
  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. }