Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract API error logic to helper #814

Merged
merged 1 commit into from
Feb 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"`
}