feat: panic on CheckErr

os.Exit(1) kill process without defering functions.
panic can be recover if needed.

Signed-off-by: Guilhem Lettron <guilhem@barpilot.io>
This commit is contained in:
Guilhem Lettron 2021-12-21 15:08:30 +01:00
parent cb9d7b1cec
commit 2b6e651ee4
2 changed files with 44 additions and 4 deletions

View file

@ -19,7 +19,6 @@ package cobra
import (
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
@ -207,11 +206,10 @@ func stringInSlice(a string, list []string) bool {
return false
}
// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
// CheckErr prints the msg with the prefix 'panic:' and exits with code != 0. If the msg is nil, it does nothing.
func CheckErr(msg interface{}) {
if msg != nil {
fmt.Fprintln(os.Stderr, "Error:", msg)
os.Exit(1)
panic(msg)
}
}

View file

@ -1,6 +1,7 @@
package cobra
import (
"errors"
"testing"
"text/template"
)
@ -26,3 +27,44 @@ func TestAddTemplateFunctions(t *testing.T) {
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
}
}
func TestCheckErr(t *testing.T) {
tests := []struct {
name string
msg interface{}
panic bool
}{
{
name: "no error",
msg: nil,
panic: false,
},
{
name: "panic string",
msg: "test",
panic: true,
},
{
name: "panic error",
msg: errors.New("test error"),
panic: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
r := recover()
if r != nil {
if !tt.panic {
t.Error("Didn't expect panic")
}
} else {
if tt.panic {
t.Error("Expected to panic")
}
}
}()
CheckErr(tt.msg)
})
}
}