github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/message/router/middleware/randomfail.go (about) 1 package middleware 2 3 import ( 4 "math/rand" 5 6 "github.com/pkg/errors" 7 "github.com/wfusion/gofusion/common/infra/watermill/message" 8 ) 9 10 func shouldFail(probability float32) bool { 11 r := rand.Float32() 12 return r <= probability 13 } 14 15 // RandomFail makes the handler fail with an error based on random chance. 16 // Error probability should be in the range (0,1). 17 func RandomFail(errorProbability float32) message.HandlerMiddleware { 18 return func(h message.HandlerFunc) message.HandlerFunc { 19 return func(message *message.Message) ([]*message.Message, error) { 20 if shouldFail(errorProbability) { 21 return nil, errors.New("random fail occurred") 22 } 23 24 return h(message) 25 } 26 } 27 } 28 29 // RandomPanic makes the handler panic based on random chance. Panic probability should be in the range (0,1). 30 func RandomPanic(panicProbability float32) message.HandlerMiddleware { 31 return func(h message.HandlerFunc) message.HandlerFunc { 32 return func(message *message.Message) ([]*message.Message, error) { 33 if shouldFail(panicProbability) { 34 panic("random panic occurred") 35 } 36 37 return h(message) 38 } 39 } 40 }