-
Notifications
You must be signed in to change notification settings - Fork 5
/
delayed.go
58 lines (48 loc) · 1.19 KB
/
delayed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package errorutil
import (
"time"
"github.com/objenious/errors"
)
// Delayer defines an error that
type Delayer interface {
Delay() time.Duration
}
// Delay return the delay duration of a DelayedError (i.e. implements Delayer).
// If the error is nil or does not implement Delayer or the delay is not a positive value, 0 is returned.
func Delay(err error) time.Duration {
type causer interface {
Cause() error
}
for err != nil {
if delay, ok := err.(Delayer); ok {
return delay.Delay()
}
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return 0
}
// DelayedError set error delay duration. returns nil if the error is nil.
func WithDelay(err error, duration time.Duration) error {
if err == nil {
return nil
}
return &delayedError{error: err, duration: duration}
}
// NewDelayedError returns a delayed error that formats as the given text and duration.
func NewDelayedError(text string, duration time.Duration) error {
return WithDelay(errors.New(text), duration)
}
type delayedError struct {
error
duration time.Duration
}
func (err *delayedError) Delay() time.Duration {
return err.duration
}
func (err *delayedError) Cause() error {
return err.error
}