retry.go 692 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package fx
  2. import "github.com/tal-tech/go-zero/core/errorx"
  3. const defaultRetryTimes = 3
  4. type (
  5. RetryOption func(*retryOptions)
  6. retryOptions struct {
  7. times int
  8. }
  9. )
  10. func DoWithRetries(fn func() error, opts ...RetryOption) error {
  11. var options = newRetryOptions()
  12. for _, opt := range opts {
  13. opt(options)
  14. }
  15. var berr errorx.BatchError
  16. for i := 0; i < options.times; i++ {
  17. if err := fn(); err != nil {
  18. berr.Add(err)
  19. } else {
  20. return nil
  21. }
  22. }
  23. return berr.Err()
  24. }
  25. func WithRetries(times int) RetryOption {
  26. return func(options *retryOptions) {
  27. options.times = times
  28. }
  29. }
  30. func newRetryOptions() *retryOptions {
  31. return &retryOptions{
  32. times: defaultRetryTimes,
  33. }
  34. }