retry-go
retry-go copied to clipboard
Getting the last retry error when cancelled by context
I have a lot of usages for retry-go (still 3.0.0) along the lines of "retry this until it succeeds or the context is done, returning the last encountered error if it didn't succeed."
I've seen the new features added in 4.x. Unfortunately, they don't match my specific use case, of course :smiley:.
I have a workaround that looks like this:
var lastErr error
retryErr := retry.Do(
func() error {
lastErr = someRetriableStuff()
return lastErr
},
retry.Context(ctx),
retry.Attempts(math.MaxUint), // could probably be retry.Attempts(0) in 4.x?
retry.LastErrorOnly(true),
)
// Prefer lastErr over retryErr: In case the context was cancelled or timed
// out, retryErr will just be the err of the context, but not the last
// encountered err of the retried function.
if retryErr != nil && lastErr != nil {
return lastErr
}
return retryErr
I'm wondering if this is something that could be supported natively by retry-go, although I'm not sure how the API could look like, given that there are already quite some interactions between Context
, Attempts
and LastErrorOnly
.
A very simple thing could be PreferContextErrors(false)
with its default being true
. This would be only effective if both Context
and LastErrorOnly(true)
are also given. Not a glorious solution, but kinda acceptable. WDYT?
Interested as well, it's even more important when you use a timeout context, you want to know when it timed-out!