-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpanick.go
More file actions
54 lines (47 loc) · 1.24 KB
/
panick.go
File metadata and controls
54 lines (47 loc) · 1.24 KB
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
package panick
import (
"crypto/rand"
"fmt"
"math/big"
"time"
)
// If panics if the condition is true
func If(condition bool, message string) {
if condition {
panic(message)
}
}
// Sometimes panics if the probability is greater than the random number generated between 0 and 100
func Sometimes(probability uint64, message string) {
n, _ := rand.Int(rand.Reader, big.NewInt(100))
rnd := n.Uint64()
if rnd < probability {
panic(message)
}
}
func OnError(err error) {
panic(err)
}
// Room creates a Panick Room and executes a function in a safe environment where
// panics are contained and returns the result or an error if a panic occurred
func Room(f func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Panick Room: %v", r)
}
}()
f()
return err
}
// RandomDelay chooses a random duration up to max and sleeps for that duration in
// a goroutine. It immediately returns the chosen duration.
func RandomDelay(max time.Duration, v any) {
n, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
r := time.Duration(n.Int64())
Delay(r, fmt.Sprintf("panick: RandomDelay %v", v))
}
// Delay sleeps for d duration and then panics.
func Delay(d time.Duration, v ...any) {
time.Sleep(d)
panic(fmt.Sprintln(v...))
}