Skip to content

Commit 7fdbb3f

Browse files
authored
feat: refactor duplicate error handling into utility function (#285)
* feat: refactor duplicate error handling into utility function Signed-off-by: ritoban23 <[email protected]> * refactor: reuse PrintFormattedError helper for consistent error logging Signed-off-by: ritoban23 <[email protected]> * style: format Go code with gofmt Signed-off-by: ritoban23 <[email protected]> --------- Signed-off-by: ritoban23 <[email protected]>
1 parent f963bb5 commit 7fdbb3f

File tree

11 files changed

+82
-20
lines changed

11 files changed

+82
-20
lines changed

pkg/cmd/create/project.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ var projectCmd = &cobra.Command{
5959
var response apis.CreateProjectResponse
6060
response, err = apis.CreateProjectRequest(projectName, credentials)
6161
if err != nil {
62-
utils.Red.Printf("❌ Error creating project: %v\n", err)
62+
utils.PrintFormattedError("Error creating project", err)
6363
} else {
6464
fmt.Printf("Response: %+v\n", response)
6565
projectID := response.Data.ID

pkg/cmd/describe/probe.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ var probeCmd = &cobra.Command{
8181
}
8282
_, option, err := prompt.Run()
8383
if err != nil {
84-
fmt.Printf("Prompt failed %v\n", err)
84+
utils.PrintFormattedError("Prompt failed", err)
8585
return
8686
}
8787
probeMode = option
@@ -90,7 +90,7 @@ var probeCmd = &cobra.Command{
9090
getProbeYAMLRequest.Mode = model.Mode(probeMode)
9191
getProbeYAML, err := apis.GetProbeYAMLRequest(pid, getProbeYAMLRequest, credentials)
9292
if err != nil {
93-
utils.Red.Println(err)
93+
utils.PrintFormattedError("Failed to fetch probe YAML", err)
9494
os.Exit(1)
9595
}
9696
getProbeYAMLData := getProbeYAML.Data.GetProbeYAML
@@ -104,7 +104,7 @@ var probeCmd = &cobra.Command{
104104
var prettyJSON bytes.Buffer
105105
err = json.Indent(&prettyJSON, jsonData, "", " ")
106106
if err != nil {
107-
utils.Red.Println("❌ Error formatting JSON: " + err.Error())
107+
utils.PrintFormattedError("Error formatting JSON", err)
108108
os.Exit(1)
109109
}
110110

pkg/cmd/get/environments.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ var GetChaosEnvironmentsCmd = &cobra.Command{
9090
for _, environment := range environmentListData[start:end] {
9191
intTime, err := strconv.ParseInt(environment.CreatedAt, 10, 64)
9292
if err != nil {
93-
fmt.Println("Error converting CreatedAt to int64:", err)
93+
utils.PrintFormattedError("Error converting CreatedAt to int64", err)
9494
continue
9595
}
9696
humanTime := time.Unix(intTime, 0)
@@ -132,12 +132,12 @@ var GetChaosEnvironmentsCmd = &cobra.Command{
132132
writer.Flush()
133133
intUpdateTime, err := strconv.ParseInt(environmentGetData.UpdatedAt, 10, 64)
134134
if err != nil {
135-
utils.Red.Println("Error converting UpdatedAt to int64:", err)
135+
utils.PrintFormattedError("Error converting UpdatedAt to int64", err)
136136
}
137137
updatedTime := time.Unix(intUpdateTime, 0).String()
138138
intCreatedTime, err := strconv.ParseInt(environmentGetData.CreatedAt, 10, 64)
139139
if err != nil {
140-
utils.Red.Println("Error converting CreatedAt to int64:", err)
140+
utils.PrintFormattedError("Error converting CreatedAt to int64", err)
141141
}
142142
createdTime := time.Unix(intCreatedTime, 0).String()
143143
writer.Flush()

pkg/cmd/get/probe.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ func getProbeList(projectID string, cmd *cobra.Command, credentials types.Creden
8686
}
8787
_, option, err := prompt.Run()
8888
if err != nil {
89-
fmt.Printf("Prompt failed %v\n", err)
89+
utils.PrintFormattedError("Prompt failed", err)
9090
return
9191
}
9292
fmt.Printf("You chose %q\n", option)
@@ -106,7 +106,7 @@ func getProbeList(projectID string, cmd *cobra.Command, credentials types.Creden
106106

107107
selectedIndex, result, err := prompt.Run()
108108
if err != nil {
109-
fmt.Printf("Prompt failed %v\n", err)
109+
utils.PrintFormattedError("Prompt failed", err)
110110
os.Exit(1)
111111
}
112112

@@ -156,7 +156,7 @@ func getProbeList(projectID string, cmd *cobra.Command, credentials types.Creden
156156
for _, probe := range probes_data[start:end] {
157157
intTime, err := strconv.ParseInt(probe.CreatedAt, 10, 64)
158158
if err != nil {
159-
fmt.Println("Error converting CreatedAt to int64:", err)
159+
utils.PrintFormattedError("Error converting CreatedAt to int64", err)
160160
continue
161161
}
162162
humanTime := time.Unix(intTime, 0)
@@ -201,12 +201,12 @@ func getProbeDetails(projectID, ProbeID string, credentials types.Credentials) {
201201
writer := tabwriter.NewWriter(os.Stdout, 30, 8, 2, '\t', tabwriter.AlignRight)
202202
intUpdateTime, err := strconv.ParseInt(probeGetData.UpdatedAt, 10, 64)
203203
if err != nil {
204-
utils.Red.Println("Error converting UpdatedAt to int64:", err)
204+
utils.PrintFormattedError("Error converting UpdatedAt to int64", err)
205205
}
206206
updatedTime := time.Unix(intUpdateTime, 0).String()
207207
intCreatedTime, err := strconv.ParseInt(probeGetData.CreatedAt, 10, 64)
208208
if err != nil {
209-
utils.Red.Println("Error converting CreatedAt to int64:", err)
209+
utils.PrintFormattedError("Error converting CreatedAt to int64", err)
210210
}
211211
createdTime := time.Unix(intCreatedTime, 0).String()
212212
utils.White_B.Fprintln(writer, "PROBE DETAILS")

pkg/cmd/save/experiment.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ var experimentCmd = &cobra.Command{
108108
// Parse experiment manifest and populate chaosExperimentInput
109109
err = utils.ParseExperimentManifest(experimentManifest, &chaosExperimentRequest)
110110
if err != nil {
111-
utils.Red.Println("❌ Error parsing Chaos Experiment manifest: " + err.Error())
111+
utils.PrintFormattedError("Error parsing Chaos Experiment manifest", err)
112112
os.Exit(1)
113113
}
114114

pkg/cmd/update/password.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ var PasswordCmd = &cobra.Command{
9999
} else {
100100
err := errors.New("Unmatched status code: " + string(bodyBytes))
101101
if err != nil {
102-
utils.Red.Println("\nError updating password: ", err)
102+
utils.PrintFormattedError("Error updating password", err)
103103
os.Exit(1)
104104
}
105105
}

pkg/infra_ops/ops.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ func ValidateSAPermissions(namespace string, mode string, kubeconfig *string) {
269269
for i, resource := range resources {
270270
pems[i], err = k8s.CheckSAPermissions(k8s.CheckSAPermissionsParams{Verb: "create", Resource: resource, Print: true, Namespace: namespace}, kubeconfig)
271271
if err != nil {
272-
utils.Red.Println(err)
272+
utils.PrintFormattedError("Permission check failed", err)
273273
}
274274
}
275275

pkg/k8s/client.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ limitations under the License.
1616
package k8s
1717

1818
import (
19+
"fmt"
1920
"os"
2021
"path/filepath"
2122

@@ -34,22 +35,22 @@ func ClientSet(kubeconfig *string) (*kubernetes.Clientset, error) {
3435
kcfg := filepath.Join(home, ".kube", "config")
3536
kubeconfig = &kcfg
3637
} else {
37-
utils.Red.Println("ERROR: Clientset generation failed!")
38+
utils.PrintFormattedError("Clientset generation failed", fmt.Errorf("home directory not found"))
3839
os.Exit(1)
3940
}
4041
}
4142

4243
// create the config
4344
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
4445
if err != nil {
45-
utils.Red.Println("ERROR: ", err.Error())
46+
utils.PrintFormattedError("Failed to build kubernetes config", err)
4647
os.Exit(1)
4748
}
4849

4950
// create the clientset
5051
clientset, err := kubernetes.NewForConfig(config)
5152
if err != nil {
52-
utils.Red.Println("ERROR: ", err.Error())
53+
utils.PrintFormattedError("Failed to create kubernetes clientset", err)
5354
os.Exit(1)
5455
}
5556
return clientset, err

pkg/utils/cliutil.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Copyright © 2021 The LitmusChaos Authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package utils
17+
18+
import (
19+
"fmt"
20+
)
21+
22+
// FormatError formats error messages consistently with appropriate emoji and styling
23+
func FormatError(message string, err error) string {
24+
return fmt.Sprintf("❌ %s: %v", message, err)
25+
}
26+
27+
// PrintFormattedError prints a formatted error message to stderr in red color
28+
func PrintFormattedError(message string, err error) {
29+
Red.Println(FormatError(message, err))
30+
}

pkg/utils/cliutil_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Copyright © 2021 The LitmusChaos Authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package utils
17+
18+
import (
19+
"errors"
20+
"testing"
21+
)
22+
23+
func TestFormatError(t *testing.T) {
24+
err := errors.New("connection failed")
25+
result := FormatError("Error creating project", err)
26+
expected := "❌ Error creating project: connection failed"
27+
28+
if result != expected {
29+
t.Errorf("FormatError() = %v, want %v", result, expected)
30+
}
31+
}

0 commit comments

Comments
 (0)