github.com/lingyao2333/mo-zero@v1.4.1/core/fx/retry.go (about) 1 package fx 2 3 import "github.com/lingyao2333/mo-zero/core/errorx" 4 5 const defaultRetryTimes = 3 6 7 type ( 8 // RetryOption defines the method to customize DoWithRetry. 9 RetryOption func(*retryOptions) 10 11 retryOptions struct { 12 times int 13 } 14 ) 15 16 // DoWithRetry runs fn, and retries if failed. Default to retry 3 times. 17 func DoWithRetry(fn func() error, opts ...RetryOption) error { 18 options := newRetryOptions() 19 for _, opt := range opts { 20 opt(options) 21 } 22 23 var berr errorx.BatchError 24 for i := 0; i < options.times; i++ { 25 if err := fn(); err != nil { 26 berr.Add(err) 27 } else { 28 return nil 29 } 30 } 31 32 return berr.Err() 33 } 34 35 // WithRetry customize a DoWithRetry call with given retry times. 36 func WithRetry(times int) RetryOption { 37 return func(options *retryOptions) { 38 options.times = times 39 } 40 } 41 42 func newRetryOptions() *retryOptions { 43 return &retryOptions{ 44 times: defaultRetryTimes, 45 } 46 }