Skip to content

Commit 432d4c1

Browse files
sggcenkalti
authored andcommitted
updates Retry to use context.Cause
This diff updates `Retry` to propagate errors using `context.Cause` instead of `Context.Err`. `context.Cause` was added in go 1.20 and allows users to propagate a specific error when cancelling a context. It is backwards compatible with `Context.Error`. * https://pkg.go.dev/context#Cause * https://pkg.go.dev/context#WithCancelCause
1 parent cb748ee commit 432d4c1

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

retry.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ func Retry[T any](ctx context.Context, operation Operation[T], opts ...RetryOpti
101101
}
102102

103103
// Stop retrying if context is cancelled.
104-
if cerr := ctx.Err(); cerr != nil {
104+
if cerr := context.Cause(ctx); cerr != nil {
105105
return res, cerr
106106
}
107107

@@ -133,7 +133,7 @@ func Retry[T any](ctx context.Context, operation Operation[T], opts ...RetryOpti
133133
select {
134134
case <-args.Timer.C():
135135
case <-ctx.Done():
136-
return res, ctx.Err()
136+
return res, context.Cause(ctx)
137137
}
138138
}
139139
}

retry_test.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,10 @@ func TestRetryContext(t *testing.T) {
8989
var cancelOn = 3
9090
var i = 0
9191

92-
ctx, cancel := context.WithCancel(context.Background())
93-
defer cancel()
92+
ctx, cancel := context.WithCancelCause(context.Background())
93+
defer cancel(context.Canceled)
94+
95+
expectedErr := errors.New("custom error")
9496

9597
// This function cancels context on "cancelOn" calls.
9698
f := func() (bool, error) {
@@ -100,7 +102,7 @@ func TestRetryContext(t *testing.T) {
100102
// cancelling the context in the operation function is not a typical
101103
// use-case, however it allows to get predictable test results.
102104
if i == cancelOn {
103-
cancel()
105+
cancel(expectedErr)
104106
}
105107

106108
log.Println("error")
@@ -111,7 +113,7 @@ func TestRetryContext(t *testing.T) {
111113
if err == nil {
112114
t.Errorf("error is unexpectedly nil")
113115
}
114-
if !errors.Is(err, context.Canceled) {
116+
if !errors.Is(err, expectedErr) {
115117
t.Errorf("unexpected error: %s", err.Error())
116118
}
117119
if i != cancelOn {

0 commit comments

Comments
 (0)