mirror of
https://github.com/duke-git/lancet.git
synced 2025-09-26 19:41:20 +08:00
perf(retry): the error returned by the Retry function contains the last error (#315)
This commit is contained in:
@@ -128,9 +128,10 @@ func Retry(retryFunc RetryFunc, opts ...Option) error {
|
||||
}
|
||||
|
||||
var i uint
|
||||
var lastErr error
|
||||
for i < config.retryTimes {
|
||||
err := retryFunc()
|
||||
if err == nil {
|
||||
lastErr = retryFunc()
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -148,7 +149,7 @@ func Retry(retryFunc RetryFunc, opts ...Option) error {
|
||||
lastSlash := strings.LastIndex(funcPath, "/")
|
||||
funcName := funcPath[lastSlash+1:]
|
||||
|
||||
return fmt.Errorf("function %s run failed after %d times retry", funcName, i)
|
||||
return fmt.Errorf("function %s run failed after %d times retry, last error: %w", funcName, i, lastErr)
|
||||
}
|
||||
|
||||
// BackoffStrategy is an interface that defines a method for calculating backoff intervals.
|
||||
|
@@ -118,7 +118,7 @@ func ExampleRetryTimes() {
|
||||
}
|
||||
|
||||
// Output:
|
||||
// function retry.ExampleRetryTimes.func1 run failed after 2 times retry
|
||||
// function retry.ExampleRetryTimes.func1 run failed after 2 times retry, last error: error occurs
|
||||
}
|
||||
|
||||
func ExampleRetry() {
|
||||
|
@@ -15,14 +15,16 @@ func TestRetryFailed(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestRetryFailed")
|
||||
|
||||
var number int
|
||||
customError := errors.New("error occurs")
|
||||
increaseNumber := func() error {
|
||||
number++
|
||||
return errors.New("error occurs")
|
||||
return customError
|
||||
}
|
||||
|
||||
err := Retry(increaseNumber, RetryWithLinearBackoff(time.Microsecond*50))
|
||||
|
||||
assert.IsNotNil(err)
|
||||
assert.Equal(errors.Is(err, customError), true)
|
||||
assert.Equal(DefaultRetryTimes, number)
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user