From d770da741471f869fb89782e8b66fc2ed5b5248e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Carlos=20Mej=C3=ADas=20Rodr=C3=ADguez?= Date: Tue, 23 Jul 2019 22:43:23 -0400 Subject: [PATCH] Enhance error printing --- cmd/stackDeploy.go | 4 ++-- common/customerrors.go | 16 ++++++++++++++-- common/types.go | 6 +++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/cmd/stackDeploy.go b/cmd/stackDeploy.go index 464a257..749ccdf 100644 --- a/cmd/stackDeploy.go +++ b/cmd/stackDeploy.go @@ -94,11 +94,11 @@ var stackDeployCmd = &cobra.Command{ common.CheckError(deploymentErr) default: // Something else happened - log.Fatalln(selectionErr) + common.CheckError(stackRetrievalErr) } default: // Something else happened - log.Fatalln(stackRetrievalErr) + common.CheckError(stackRetrievalErr) } }, } diff --git a/common/customerrors.go b/common/customerrors.go index d472600..529ee84 100644 --- a/common/customerrors.go +++ b/common/customerrors.go @@ -1,7 +1,11 @@ package common import ( + "bytes" "encoding/json" + "errors" + "fmt" + "io/ioutil" "log" "net/http" ) @@ -9,16 +13,24 @@ import ( // CheckError checks if an error occurred (it's not nil) func CheckError(err error) { if err != nil { - log.Fatalln(err) + log.Fatalln(fmt.Sprintf("Error: %s", err.Error())) } } func CheckResponseForErrors(resp *http.Response) error { if 300 <= resp.StatusCode { + // Guess it's a GenericError respBody := GenericError{} err := json.NewDecoder(resp.Body).Decode(&respBody) if err != nil { - return err + // It's not a GenericError + bodyBytes, err := ioutil.ReadAll(resp.Body) + defer resp.Body.Close() + if err != nil { + return err + } + resp.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) + return errors.New(string(bodyBytes)) } return &respBody } diff --git a/common/types.go b/common/types.go index d892f5c..b9daa78 100644 --- a/common/types.go +++ b/common/types.go @@ -70,7 +70,11 @@ type GenericError struct { } func (e *GenericError) Error() string { - return fmt.Sprintf("%s: %s", e.Err, e.Details) + if e.Details != "" { + return fmt.Sprintf("%s: %s", e.Err, e.Details) + } else { + return fmt.Sprintf("%s", e.Err) + } } type AuthenticateUserRequest struct {