Move panics up to main function

This commit is contained in:
IamTheFij 2019-10-04 16:17:36 -07:00
parent 1ad5bcef14
commit 6b9edf75d7
2 changed files with 30 additions and 34 deletions

14
main.go
View File

@ -15,7 +15,7 @@ var (
version = "dev"
)
func checkMonitors(config *Config) {
func checkMonitors(config *Config) error {
for _, monitor := range config.Monitors {
if monitor.ShouldCheck() {
_, alertNotice := monitor.Check()
@ -43,13 +43,12 @@ func checkMonitors(config *Config) {
err,
output,
)
// TODO: Maybe return this error instead of panicking here
panic(fmt.Errorf(
return fmt.Errorf(
"ERROR: Unsuccessfully triggered alert '%s'. "+
"Crashing to avoid false negatives: %v",
alert.Name,
err,
))
)
}
} else {
// TODO: Maybe panic here. Also, probably validate up front
@ -59,6 +58,8 @@ func checkMonitors(config *Config) {
}
}
}
return nil
}
func main() {
@ -81,7 +82,10 @@ func main() {
// Start main loop
for {
checkMonitors(&config)
err = checkMonitors(&config)
if err != nil {
panic(err)
}
sleepTime := time.Duration(config.CheckInterval) * time.Second
time.Sleep(sleepTime)

View File

@ -5,12 +5,12 @@ import "testing"
func TestCheckMonitors(t *testing.T) {
cases := []struct {
config Config
expectPanic bool
expectErr bool
name string
}{
{
config: Config{},
expectPanic: false,
expectErr: false,
name: "Empty",
},
{
@ -22,7 +22,7 @@ func TestCheckMonitors(t *testing.T) {
},
},
},
expectPanic: false,
expectErr: false,
name: "Monitor success, no alerts",
},
{
@ -41,7 +41,7 @@ func TestCheckMonitors(t *testing.T) {
},
},
},
expectPanic: false,
expectErr: false,
name: "Monitor failure, no and unknown alerts",
},
{
@ -60,7 +60,7 @@ func TestCheckMonitors(t *testing.T) {
},
},
},
expectPanic: false,
expectErr: false,
name: "Monitor recovery, no alerts",
},
{
@ -79,7 +79,7 @@ func TestCheckMonitors(t *testing.T) {
},
},
},
expectPanic: false,
expectErr: false,
name: "Monitor failure, successful alert",
},
{
@ -99,24 +99,16 @@ func TestCheckMonitors(t *testing.T) {
},
},
},
expectPanic: true,
expectErr: true,
name: "Monitor failure, bad alert",
},
}
for _, c := range cases {
// Create new function so that deferred recovery can run at end of each test case
func() {
// Set up recover to catch panic
defer func() {
if r := recover(); r == nil {
if c.expectPanic {
c.config.Init()
err := checkMonitors(&c.config)
if err == nil && c.expectErr {
t.Errorf("checkMonitors(%s): Expected panic, the code did not panic", c.name)
}
}
}()
c.config.Init()
checkMonitors(&c.config)
}()
}
}