ceph: assert error type before using it

We don't always get an error of the type "*exec.ExitError" so we must
validate the type before printing it otherwise the interface conversion
will fail.

Signed-off-by: Sébastien Han <seb@redhat.com>
This commit is contained in:
Sébastien Han committed 2020-10-28 17:08:38 +01:00
1 parent 3dccee9a42
commit 1168dbc6ca
2 files changed
+58 -2

No files matched your search

+13 -2
View File
@@ -200,7 +200,7 @@ func (*CommandExecutor) ExecuteCommandWithOutputFile(command, outfileArg string,
cmd := exec.Command(command, arg...)
cmdOut, err := cmd.CombinedOutput()
if err != nil {
cmdOut = []byte(fmt.Sprintf("%s. %s", string(cmdOut), string(err.(*exec.ExitError).Stderr)))
cmdOut = []byte(fmt.Sprintf("%s. %s", string(cmdOut), assertErrorType(err)))
}
// if there was anything that went to stdout/stderr then log it, even before we return an error
if string(cmdOut) != "" {
@@ -282,7 +282,7 @@ func runCommandWithOutput(cmd *exec.Cmd, combinedOutput bool) (string, error) {
} else {
output, err = cmd.Output()
if err != nil {
output = []byte(fmt.Sprintf("%s. %s", string(output), string(err.(*exec.ExitError).Stderr)))
output = []byte(fmt.Sprintf("%s. %s", string(output), assertErrorType(err)))
}
}
@@ -298,3 +298,14 @@ func runCommandWithOutput(cmd *exec.Cmd, combinedOutput bool) (string, error) {
func logCommand(command string, arg ...string) {
logger.Debugf("Running command: %s %s", command, strings.Join(arg, " "))
}
func assertErrorType(err error) string {
switch errType := err.(type) {
case *exec.ExitError:
return string(errType.Stderr)
case *exec.Error:
return errType.Error()
}
return ""
}
+45
View File
@@ -0,0 +1,45 @@
/*
Copyright 2020 The Rook Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package exec
import (
"errors"
"os/exec"
"testing"
)
func Test_assertErrorType(t *testing.T) {
type args struct {
err error
}
tests := []struct {
name string
args args
want string
}{
{"unknown error type", args{err: errors.New("i don't know this error")}, ""},
{"exec.exitError type", args{err: &exec.ExitError{Stderr: []byte("this is an error")}}, "this is an error"},
{"exec.Error type", args{err: &exec.Error{Name: "my error", Err: errors.New("this is an error")}}, "exec: \"my error\": this is an error"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := assertErrorType(tt.args.err); got != tt.want {
t.Errorf("assertErrorType() = %v, want %v", got, tt.want)
}
})
}
}