-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
error.go
52 lines (44 loc) · 938 Bytes
/
error.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
package async
// based on https://github.com/Gurpartap/async
// Apache-2.0 License, see https://github.com/Gurpartap/async/blob/master/License.txt
import (
"context"
"golang.org/x/xerrors"
)
type ErrorFuture interface {
Await() error
AwaitContext(ctx context.Context) error
}
type errorFuture struct {
await func(ctx context.Context) error
}
func (f errorFuture) Await() error {
return f.await(context.Background())
}
func (f errorFuture) AwaitContext(ctx context.Context) error {
return f.await(ctx)
}
func Err(f func() error) ErrorFuture {
var err error
c := make(chan struct{}, 1)
go func() {
defer close(c)
defer func() {
if rerr := recover(); rerr != nil {
err = xerrors.Errorf("async error: %s", rerr)
return
}
}()
err = f()
}()
return errorFuture{
await: func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c:
return err
}
},
}
}