sugar/errors.go

52 lines
1019 B
Go
Raw Normal View History

package sugar
import (
"fmt"
"os"
)
var (
ErrorWriter = os.Stderr
ErrorPrefix = "Error:"
ErrorFmt = "%s %+v"
StandardExitCode = 1
PanicFunc = func(err error) {
panic(err)
}
ErrorPrintFunc = func(err error) {
fmt.Fprintf(ErrorWriter, ErrorFmt, ErrorPrefix, err)
}
ExitFunc = func(code int) {
os.Exit(code)
}
)
// Check takes an error and prints it if it is not nil; but will continue.
func Check(err error) {
if err != nil {
ErrorPrintFunc(err)
}
}
// CheckPanic takes an error and will panic if it is not nil.
func CheckPanic(err error) {
if err != nil {
PanicFunc(err)
}
}
// CheckExit takes an error and will print it and exit if it is not nil.
// If no exit code is provided, the StandardExitCode will be used.
// Any exit codes beyond the first one one provided will be discarded.
func CheckExit(err error, code ...int) {
if err != nil {
ErrorPrintFunc(err)
exitCode := StandardExitCode
if len(code) > 0 {
exitCode = code[0]
}
ExitFunc(exitCode)
}
}