@@ -50,6 +50,8 @@ type Retrier struct {
50
50
mutex sync.RWMutex
51
51
// timer is the timer used to timeout the retry function.
52
52
timer * time.Timer
53
+ // err is the error returned by the retry function.
54
+ err error
53
55
}
54
56
55
57
// NewRetrier returns a new Retrier.
@@ -93,21 +95,18 @@ func (r *Retrier) Retry(fn func() error, temporaryErrors ...string) error {
93
95
// defer stop the timer for the timeout.
94
96
defer r .timer .Stop ()
95
97
96
- // Initialize a variable to store the error returned by the function.
97
- var err error
98
-
99
98
// Retry the function until it returns a nil error or the maximum number of retries is reached.
100
99
for i := 0 ; i < r .MaxRetries ; i ++ {
101
100
// Call the function.
102
- err = fn ()
101
+ r . err = fn ()
103
102
104
103
// If the function returns a nil error, return nil.
105
- if err == nil {
104
+ if r . err == nil {
106
105
return nil
107
106
}
108
107
109
108
// Check if the error returned by the function is temporary when the list of temporary errors is not empty.
110
- if len (temporaryErrors ) > 0 && ! r .IsTemporaryError (err , temporaryErrors ... ) {
109
+ if len (temporaryErrors ) > 0 && ! r .IsTemporaryError (r . err , temporaryErrors ... ) {
111
110
break
112
111
}
113
112
@@ -116,7 +115,7 @@ func (r *Retrier) Retry(fn func() error, temporaryErrors ...string) error {
116
115
select {
117
116
case <- r .timer .C :
118
117
// Return an error if the timeout is reached.
119
- return fmt .Errorf ("timeout reached after %v: %w" , r .Timeout , err )
118
+ return fmt .Errorf ("timeout reached after %v: %w" , r .Timeout , r . err )
120
119
case <- time .After (sleepDuration ):
121
120
// Continue the loop if the sleep duration expires.
122
121
}
@@ -125,7 +124,7 @@ func (r *Retrier) Retry(fn func() error, temporaryErrors ...string) error {
125
124
// Return an error indicating that the maximum number of retries was reached.
126
125
retryErr := retryErrorPool .Get ().(* RetryError )
127
126
retryErr .MaxRetries = r .MaxRetries
128
- retryErr .Err = err
127
+ retryErr .Err = r . err
129
128
return retryErr
130
129
}
131
130
0 commit comments