Skip to content

Commit 8071dc2

Browse files
jdsutherlandKatrina Owen
authored andcommitted
Extract API error logic to helper
The submit command handles API errors correctly. We need to be able to share this logic so we can stop swallowing errors in other commands.
1 parent 2f5ff0a commit 8071dc2

File tree

2 files changed

+21
-14
lines changed

2 files changed

+21
-14
lines changed

cmd/cmd.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package cmd
22

33
import (
4+
"encoding/json"
45
"fmt"
6+
"net/http"
57

68
"io"
79

@@ -70,3 +72,21 @@ func validateUserConfig(cfg *viper.Viper) error {
7072
}
7173
return nil
7274
}
75+
76+
// decodedAPIError decodes and returns the error message from the API response.
77+
// If the message is blank, it returns a fallback message with the status code.
78+
func decodedAPIError(resp *http.Response) error {
79+
var apiError struct {
80+
Error struct {
81+
Type string `json:"type"`
82+
Message string `json:"message"`
83+
} `json:"error,omitempty"`
84+
}
85+
if err := json.NewDecoder(resp.Body).Decode(&apiError); err != nil {
86+
return fmt.Errorf("failed to parse API error response: %s", err)
87+
}
88+
if apiError.Error.Message != "" {
89+
return fmt.Errorf(apiError.Error.Message)
90+
}
91+
return fmt.Errorf("unexpected API response: %d", resp.StatusCode)
92+
}

cmd/submit.go

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package cmd
22

33
import (
44
"bytes"
5-
"encoding/json"
65
"errors"
76
"fmt"
87
"io"
@@ -254,12 +253,7 @@ func (s *submitCmdContext) submit(metadata *workspace.ExerciseMetadata, docs []w
254253
defer resp.Body.Close()
255254

256255
if resp.StatusCode == http.StatusBadRequest {
257-
var jsonErrBody apiErrorMessage
258-
if err := json.NewDecoder(resp.Body).Decode(&jsonErrBody); err != nil {
259-
return fmt.Errorf("failed to parse error response - %s", err)
260-
}
261-
262-
return fmt.Errorf(jsonErrBody.Error.Message)
256+
return decodedAPIError(resp)
263257
}
264258

265259
bb := &bytes.Buffer{}
@@ -430,10 +424,3 @@ func (s submitValidator) isRequestor(metadata *workspace.ExerciseMetadata) error
430424
func init() {
431425
RootCmd.AddCommand(submitCmd)
432426
}
433-
434-
type apiErrorMessage struct {
435-
Error struct {
436-
Type string `json:"type"`
437-
Message string `json:"message"`
438-
} `json:"error,omitempty"`
439-
}

0 commit comments

Comments
 (0)