-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherr.go
58 lines (48 loc) · 1008 Bytes
/
err.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 bctx
import (
"context"
"sync"
)
type CancelErrFunc func(error)
// WithCancelError returns a context that can return a custom error for cancelation.
// the error returned from `Err()` would return true for `xerrors.Is(err, context.Canceled)`.
func WithCancelError(ctx Context) (Context, CancelErrFunc) {
ctx, fn := WithCancel(ctx)
ectx := &errCtx{Context: ctx, fn: fn}
return ectx, ectx.cancel
}
type errCtx struct {
context.Context
fn CancelFunc
mux sync.Mutex
err error
}
func (ec *errCtx) Err() error {
ec.mux.Lock()
err := ec.err
ec.mux.Unlock()
if err == nil {
err = ec.Context.Err()
}
return err
}
func (ec *errCtx) cancel(err error) {
ec.mux.Lock()
if ec.err == nil {
ec.fn()
ec.err = &cancelError{err}
}
ec.mux.Unlock()
}
type cancelError struct {
e error
}
func (ce cancelError) Error() string {
return ce.e.Error()
}
func (ce cancelError) Is(oe error) bool {
return oe == ce.e || oe == Canceled
}
func (ce cancelError) Unwrap() error {
return ce.e
}