error_handler.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package errors
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/fatih/color"
  6. "github.com/getsentry/sentry-go"
  7. "github.com/porter-dev/porter/cli/cmd/config"
  8. )
  9. var SentryDSN string = ""
  10. type errorHandler interface {
  11. HandleError(error)
  12. }
  13. type standardErrorHandler struct{}
  14. func (h *standardErrorHandler) HandleError(err error) {
  15. color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
  16. }
  17. type sentryErrorHandler struct{}
  18. func (h *sentryErrorHandler) HandleError(err error) {
  19. if SentryDSN == "" {
  20. panic("using SentryErrorHandler but Sentry DSN is not set")
  21. }
  22. localHub := sentry.CurrentHub().Clone()
  23. localHub.ConfigureScope(func(scope *sentry.Scope) {
  24. scope.SetTags(map[string]string{
  25. "host": config.GetCLIConfig().Host,
  26. "project": fmt.Sprintf("%d", config.GetCLIConfig().Project),
  27. "cluster": fmt.Sprintf("%d", config.GetCLIConfig().Cluster),
  28. })
  29. })
  30. if eventID := localHub.CaptureException(err); eventID == nil {
  31. color.New(color.FgRed).Fprintf(os.Stderr, "error in sending exception to sentry\n")
  32. }
  33. color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
  34. }
  35. func GetErrorHandler() errorHandler {
  36. if SentryDSN != "" {
  37. return &sentryErrorHandler{}
  38. }
  39. return &standardErrorHandler{}
  40. }