error.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package prom
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // WrapError wraps the given error with the given message, usually for adding
  7. // context, but persists the existing type of error.
  8. func WrapError(err error, msg string) error {
  9. switch e := err.(type) {
  10. case CommError:
  11. return e.Wrap(msg)
  12. case NoDataError:
  13. return e.Wrap(msg)
  14. default:
  15. return fmt.Errorf("%s: %s", msg, err)
  16. }
  17. }
  18. // CommError describes an error communicating with Prometheus
  19. type CommError struct {
  20. messages []string
  21. }
  22. // NewCommError creates a new CommError
  23. func NewCommError(messages ...string) CommError {
  24. return CommError{messages: messages}
  25. }
  26. // IsCommError returns true if the given error is a CommError
  27. func IsCommError(err error) bool {
  28. _, ok := err.(CommError)
  29. return ok
  30. }
  31. // Error prints the error as a string
  32. func (pce CommError) Error() string {
  33. return fmt.Sprintf("Prometheus communication error: %s", strings.Join(pce.messages, ": "))
  34. }
  35. // Wrap wraps the error with the given message, but persists the error type.
  36. func (pce CommError) Wrap(message string) CommError {
  37. pce.messages = append([]string{message}, pce.messages...)
  38. return pce
  39. }
  40. // NoDataError indicates that no data was returned by Prometheus. This should
  41. // be treated like an EOF error, in that it may be expected.
  42. type NoDataError struct {
  43. messages []string
  44. }
  45. // NewNoDataError creates a new NoDataError
  46. func NewNoDataError(messages ...string) NoDataError {
  47. return NoDataError{messages: messages}
  48. }
  49. // IsNoDataError returns true if the given error is a NoDataError
  50. func IsNoDataError(err error) bool {
  51. _, ok := err.(NoDataError)
  52. return ok
  53. }
  54. // Error prints the error as a string
  55. func (nde NoDataError) Error() string {
  56. return fmt.Sprintf("No data error: %s", strings.Join(nde.messages, ": "))
  57. }
  58. // Wrap wraps the error with the given message, but persists the error type.
  59. func (nde NoDataError) Wrap(message string) NoDataError {
  60. nde.messages = append([]string{message}, nde.messages...)
  61. return nde
  62. }