Skip to content

Commit defb54d

Browse files
committed
rate: add limiter sentinel errors
This lets users check for the type of error more easily. The change is also backwards compatible for users that may use error string based comparisons as a workaround.
1 parent 7e3f01d commit defb54d

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

rate/rate.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package rate
77

88
import (
99
"context"
10+
"errors"
1011
"fmt"
1112
"math"
1213
"sync"
@@ -29,6 +30,16 @@ func Every(interval time.Duration) Limit {
2930
return 1 / Limit(interval.Seconds())
3031
}
3132

33+
var (
34+
// ErrExceedsBurst is returned when the limiter's burst is exceeded. The
35+
// error is wrapped with additional context.
36+
ErrExceedsBurst = errors.New("exceeds limiter's burst")
37+
38+
// ErrWouldExceedDeadline is returned when the limiter's deadline would be
39+
// exceeded. The error is wrapped with additional context.
40+
ErrWouldExceedDeadline = errors.New("would exceed context deadline")
41+
)
42+
3243
// A Limiter controls how frequently events are allowed to happen.
3344
// It implements a "token bucket" of size b, initially full and refilled
3445
// at rate r tokens per second.
@@ -230,7 +241,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
230241
lim.mu.Unlock()
231242

232243
if n > burst && limit != Inf {
233-
return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst)
244+
return fmt.Errorf("rate: Wait(n=%d) %w %d", n, ErrExceedsBurst, burst)
234245
}
235246
// Check if ctx is already cancelled
236247
select {
@@ -247,7 +258,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
247258
// Reserve
248259
r := lim.reserveN(now, n, waitLimit)
249260
if !r.ok {
250-
return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
261+
return fmt.Errorf("rate: Wait(n=%d) %w", n, ErrWouldExceedDeadline)
251262
}
252263
// Wait if necessary
253264
delay := r.DelayFrom(now)

0 commit comments

Comments
 (0)