error_handler.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package errors
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. "github.com/fatih/color"
  7. "github.com/getsentry/sentry-go"
  8. "github.com/porter-dev/porter/cli/cmd/config"
  9. )
  10. // SentryDSN is a global value for sentry's dsn. This should be removed
  11. var SentryDSN string = ""
  12. type errorHandler interface {
  13. HandleError(error)
  14. }
  15. type standardErrorHandler struct{}
  16. // HandleError implements errorhandler for handling non-sentry errors
  17. func (h *standardErrorHandler) HandleError(err error) {
  18. color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
  19. }
  20. type sentryErrorHandler struct {
  21. cliConfig config.CLIConfig
  22. }
  23. // HandleError implements errorhandler for handling sentry errors
  24. func (h *sentryErrorHandler) HandleError(err error) {
  25. if SentryDSN != "" {
  26. localHub := sentry.CurrentHub().Clone()
  27. localHub.ConfigureScope(func(scope *sentry.Scope) {
  28. scope.SetTags(map[string]string{
  29. "host": h.cliConfig.Host,
  30. "project": fmt.Sprintf("%d", h.cliConfig.Project),
  31. "cluster": fmt.Sprintf("%d", h.cliConfig.Cluster),
  32. })
  33. })
  34. localHub.CaptureException(err)
  35. sentry.Flush(2 * time.Second)
  36. }
  37. color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
  38. }
  39. // GetErrorHandler returns an errorhandler.
  40. func GetErrorHandler(cliConf config.CLIConfig) errorHandler {
  41. if SentryDSN != "" {
  42. return &sentryErrorHandler{
  43. cliConfig: cliConf,
  44. }
  45. }
  46. return &standardErrorHandler{}
  47. }