Skip to content

Commit 1ce8f43

Browse files
committed
Refactor error handling
1 parent 5f1dd6e commit 1ce8f43

File tree

1 file changed

+27
-22
lines changed

1 file changed

+27
-22
lines changed

cmd/notigo/main.go

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,27 +12,17 @@ import (
1212
func main() {
1313
var opt options
1414
args, err := flags.Parse(&opt)
15-
if err != nil {
16-
_, _ = fmt.Fprintln(os.Stderr, "cannot parse options:", err)
17-
os.Exit(1)
18-
}
15+
exitWithTextIfError("cannot parse options:", err)
1916

2017
keys, err := findKeys(opt)
21-
if err != nil {
22-
_, _ = fmt.Fprintln(os.Stderr, "cannot find IFTTT key(s):", err)
23-
os.Exit(1)
24-
}
18+
exitWithTextIfError("cannot find IFTTT key(s):", err)
2519

2620
if len(keys) == 0 {
27-
_, _ = fmt.Fprintln(os.Stderr, "no IFTTT key(s) found")
28-
os.Exit(1)
21+
exitWithText("no IFTTT key(s) found")
2922
}
3023

3124
messages, err := findMessages(opt, args)
32-
if err != nil {
33-
_, _ = fmt.Fprintln(os.Stderr, "cannot find messages:", err)
34-
os.Exit(1)
35-
}
25+
exitWithTextIfError("cannot find messages:", err)
3626

3727
if len(messages) == 0 {
3828
messages = []string{" "}
@@ -48,22 +38,22 @@ func main() {
4838
}(key)
4939
}
5040

51-
var err error
41+
hasError := false
5242
for range keys {
53-
err = <-errorChan
43+
err := <-errorChan
44+
if err != nil {
45+
printError("cannot send notification:", err)
46+
hasError = true
47+
}
5448
}
5549

56-
if err != nil {
57-
_, _ = fmt.Fprintln(os.Stderr, "cannot send notification:", err)
50+
if hasError {
5851
os.Exit(1)
5952
}
6053
} else {
6154
for _, key := range keys {
6255
err := sendNotifications(key, opt.Event, opt.Title, messages, opt.Delay)
63-
if err != nil {
64-
_, _ = fmt.Fprintln(os.Stderr, "cannot send notification:", err)
65-
os.Exit(1)
66-
}
56+
exitWithTextIfError("cannot send notification:", err)
6757
}
6858
}
6959
}
@@ -90,3 +80,18 @@ func sendNotifications(key Key, event, title string, messages []string, delay ti
9080

9181
return nil
9282
}
83+
84+
func printError(args ...interface{}) {
85+
_, _ = fmt.Fprintln(os.Stderr, args...)
86+
}
87+
88+
func exitWithText(args ...interface{}) {
89+
printError(args...)
90+
os.Exit(1)
91+
}
92+
93+
func exitWithTextIfError(text string, err error) {
94+
if err != nil {
95+
exitWithText(text, err.Error())
96+
}
97+
}

0 commit comments

Comments
 (0)