Retry - Core helpers
This page lists all retry operations available in the core package of lo.
Help improve this documentation
This documentation is still new and evolving. If you spot any mistakes, unclear explanations, or missing details, please open an issue.
Your feedback helps us improve!
Attemptโ
Invokes a function up to N times until it returns nil. Returns the number of iterations attempted (1-based) and the last error. Useful for retrying operations that might fail temporarily.
// Success after 3 attemptsiter, err := lo.Attempt(5, func(i int) error {if i == 2 {return nil // succeeds on 3rd attempt (index 2)}return errors.New("failed")})// iter: 3, err: nil// All attempts fail - returns last erroriter, err = lo.Attempt(3, func(i int) error {return fmt.Errorf("attempt %d failed", i)})// iter: 3, err: "attempt 2 failed" (last error from index 2)// Immediate success on first attemptiter, err = lo.Attempt(5, func(i int) error {return nil // succeeds immediately})// iter: 1, err: nil// Zero attempts - returns error without calling functioniter, err = lo.Attempt(0, func(i int) error {return errors.New("should not be called")})// iter: 0, err: "maxIteration must be greater than 0"Prototype:func Attempt(maxIteration int, f func(index int) error) (int, error)AttemptWithDelayโ
Invokes a function up to N times with a pause between calls until it returns nil. Returns iterations, elapsed, and error.
iter, dur, err := lo.AttemptWithDelay(3,100*time.Millisecond,func(i int, d time.Duration) error {if i == 1 {return nil}return errors.New("x")},)Prototype:func AttemptWithDelay(maxIteration int, delay time.Duration, f func(index int, duration time.Duration) error) (int, time.Duration, error)AttemptWhileโ
Invokes a function up to N times until it returns nil. The second return value controls whether to continue attempting.
count, err := lo.AttemptWhile(5, func(i int) (error, bool) {if i == 2 {return nil, false}return errors.New("fail"), true})// count == 3, err == nilPrototype:func AttemptWhile(maxIteration int, f func(int) (error, bool)) (int, error)AttemptWhileWithDelayโ
Like AttemptWhile, but pauses between attempts and returns elapsed time.
count, dur, err := lo.AttemptWhileWithDelay(5,time.Millisecond,func(i int, d time.Duration) (error, bool) {return errors.New("x"), i < 1},)Prototype:func AttemptWhileWithDelay(maxIteration int, delay time.Duration, f func(int, time.Duration) (error, bool)) (int, time.Duration, error)