classifier.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package retrier
  2. // Action is the type returned by a Classifier to indicate how the Retrier should proceed.
  3. type Action int
  4. const (
  5. Succeed Action = iota // Succeed indicates the Retrier should treat this value as a success.
  6. Fail // Fail indicates the Retrier should treat this value as a hard failure and not retry.
  7. Retry // Retry indicates the Retrier should treat this value as a soft failure and retry.
  8. )
  9. // Classifier is the interface implemented by anything that can classify Errors for a Retrier.
  10. type Classifier interface {
  11. Classify(error) Action
  12. }
  13. // DefaultClassifier classifies errors in the simplest way possible. If
  14. // the error is nil, it returns Succeed, otherwise it returns Retry.
  15. type DefaultClassifier struct{}
  16. // Classify implements the Classifier interface.
  17. func (c DefaultClassifier) Classify(err error) Action {
  18. if err == nil {
  19. return Succeed
  20. }
  21. return Retry
  22. }
  23. // WhitelistClassifier classifies errors based on a whitelist. If the error is nil, it
  24. // returns Succeed; if the error is in the whitelist, it returns Retry; otherwise, it returns Fail.
  25. type WhitelistClassifier []error
  26. // Classify implements the Classifier interface.
  27. func (list WhitelistClassifier) Classify(err error) Action {
  28. if err == nil {
  29. return Succeed
  30. }
  31. for _, pass := range list {
  32. if err == pass {
  33. return Retry
  34. }
  35. }
  36. return Fail
  37. }
  38. // BlacklistClassifier classifies errors based on a blacklist. If the error is nil, it
  39. // returns Succeed; if the error is in the blacklist, it returns Fail; otherwise, it returns Retry.
  40. type BlacklistClassifier []error
  41. // Classify implements the Classifier interface.
  42. func (list BlacklistClassifier) Classify(err error) Action {
  43. if err == nil {
  44. return Succeed
  45. }
  46. for _, pass := range list {
  47. if err == pass {
  48. return Fail
  49. }
  50. }
  51. return Retry
  52. }