forked from OneOfOne/go-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added DieIf/PrintfIf to help with errors
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package errors | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
) | ||
|
||
// DieIf prints msg + err to stderr then exits the program with status code 1 | ||
// it's like a panic, without the stacktrace. | ||
// use %v in message to print the error, default is "error: %v" | ||
func DieIf(err error, msg string) { | ||
if err != nil { | ||
if len(msg) == 0 { | ||
msg = "error: %v" | ||
} | ||
fmt.Fprintf(os.Stderr, msg+"\n", err) | ||
os.Exit(1) | ||
} | ||
} | ||
|
||
// PrintfIf calls fn (log.Printf or fmt.Printf for example) with msg and err | ||
// if err != nil, it will return true and call fn(msg, err) | ||
// example: | ||
// if PrintfIf(err, "error: %v\n", log.Printf) { | ||
// return | ||
// } | ||
func PrintfIf(err error, msg string, fn func(format string, args ...interface{})) (b bool) { | ||
if b = err != nil; b { | ||
if len(msg) == 0 { | ||
msg = "error: %v" | ||
} | ||
fn(msg, err) | ||
} | ||
return | ||
} |