-
Notifications
You must be signed in to change notification settings - Fork 8
/
op_switch_if_error.go
53 lines (47 loc) · 1.18 KB
/
op_switch_if_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
53
package mono
import (
"context"
"github.com/jjeffcaii/reactor-go"
"github.com/jjeffcaii/reactor-go/internal/subscribers"
"github.com/pkg/errors"
)
type monoSwitchIfError struct {
source reactor.RawPublisher
sw func(error) Mono
}
func (m monoSwitchIfError) Parent() reactor.RawPublisher {
return m.source
}
func (m monoSwitchIfError) SubscribeWith(ctx context.Context, actual reactor.Subscriber) {
alternative := func(err error) (pub reactor.RawPublisher) {
if m.sw == nil {
pub = newMonoError(errors.New("the SwitchIfError transform is nil"))
return
}
defer func() {
rec := recover()
if rec == nil {
return
}
if e, ok := rec.(error); ok {
pub = newMonoError(errors.WithStack(e))
} else {
pub = newMonoError(errors.Errorf("%v", rec))
}
}()
pub = m.sw(err)
if pub == nil {
pub = newMonoError(errors.New("the SwitchIfError returns nil Mono"))
}
return
}
s := subscribers.NewSwitchIfErrorSubscriber(alternative, actual)
actual.OnSubscribe(ctx, s)
m.source.SubscribeWith(ctx, s)
}
func newMonoSwitchIfError(source reactor.RawPublisher, sw func(error) Mono) monoSwitchIfError {
return monoSwitchIfError{
source: source,
sw: sw,
}
}