Skip to content

Commit

Permalink
Extract API error logic to helper
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jdsutherland authored and Katrina Owen committed Feb 26, 2019
1 parent 2f5ff0a commit 8071dc2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
20 changes: 20 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package cmd

import (
"encoding/json"
"fmt"
"net/http"

"io"

Expand Down Expand Up @@ -70,3 +72,21 @@ func validateUserConfig(cfg *viper.Viper) error {
}
return nil
}

// decodedAPIError decodes and returns the error message from the API response.
// If the message is blank, it returns a fallback message with the status code.
func decodedAPIError(resp *http.Response) error {
var apiError struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
if err := json.NewDecoder(resp.Body).Decode(&apiError); err != nil {
return fmt.Errorf("failed to parse API error response: %s", err)
}
if apiError.Error.Message != "" {
return fmt.Errorf(apiError.Error.Message)
}
return fmt.Errorf("unexpected API response: %d", resp.StatusCode)
}
15 changes: 1 addition & 14 deletions cmd/submit.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -254,12 +253,7 @@ func (s *submitCmdContext) submit(metadata *workspace.ExerciseMetadata, docs []w
defer resp.Body.Close()

if resp.StatusCode == http.StatusBadRequest {
var jsonErrBody apiErrorMessage
if err := json.NewDecoder(resp.Body).Decode(&jsonErrBody); err != nil {
return fmt.Errorf("failed to parse error response - %s", err)
}

return fmt.Errorf(jsonErrBody.Error.Message)
return decodedAPIError(resp)
}

bb := &bytes.Buffer{}
Expand Down Expand Up @@ -430,10 +424,3 @@ func (s submitValidator) isRequestor(metadata *workspace.ExerciseMetadata) error
func init() {
RootCmd.AddCommand(submitCmd)
}

type apiErrorMessage struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error,omitempty"`
}

0 comments on commit 8071dc2

Please sign in to comment.