/
randomfail.go
40 lines (33 loc) · 1.07 KB
/
randomfail.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
package middleware
import (
"math/rand"
"github.com/pkg/errors"
"github.com/wfusion/gofusion/common/infra/watermill/message"
)
func shouldFail(probability float32) bool {
r := rand.Float32()
return r <= probability
}
// RandomFail makes the handler fail with an error based on random chance.
// Error probability should be in the range (0,1).
func RandomFail(errorProbability float32) message.HandlerMiddleware {
return func(h message.HandlerFunc) message.HandlerFunc {
return func(message *message.Message) ([]*message.Message, error) {
if shouldFail(errorProbability) {
return nil, errors.New("random fail occurred")
}
return h(message)
}
}
}
// RandomPanic makes the handler panic based on random chance. Panic probability should be in the range (0,1).
func RandomPanic(panicProbability float32) message.HandlerMiddleware {
return func(h message.HandlerFunc) message.HandlerFunc {
return func(message *message.Message) ([]*message.Message, error) {
if shouldFail(panicProbability) {
panic("random panic occurred")
}
return h(message)
}
}
}