Skip to content

Commit

Permalink
Download non-200 response no longer swallowed
Browse files Browse the repository at this point in the history
Based on exercism#794, we've decide to
error out and display API error messages.

This overlaps with cmd/submit, so this change extracts it for sharing.
  • Loading branch information
jdsutherland committed Feb 21, 2019
1 parent fa6b272 commit f0f6424
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
19 changes: 16 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ func validateUserConfig(cfg *viper.Viper) error {
return nil
}

func decodedAPIErrorResponse(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 error response - %s", err)
}

return fmt.Errorf(apiError.Error.Message)
}

// download is a download from the Exercism API.
type download struct {
params *downloadParams
Expand Down Expand Up @@ -250,7 +264,7 @@ type solutionFileRequester struct {
}

// request requests a Solution file from the API, returning an HTTP response.
// Non-200 responses and 0 Content-Length responses are swallowed, returning nil.
// 0 Content-Length responses are swallowed, returning nil.
func (s solutionFileRequester) request(filename string) (*http.Response, error) {
parsedURL, err := netURL.ParseRequestURI(
fmt.Sprintf("%s%s", s.download.Solution.FileDownloadBaseURL, filename))
Expand All @@ -269,8 +283,7 @@ func (s solutionFileRequester) request(filename string) (*http.Response, error)
}

if res.StatusCode != http.StatusOK {
// TODO: deal with it
return nil, nil
return nil, decodedAPIErrorResponse(res)
}
// Don't bother with empty files.
if res.Header.Get("Content-Length") == "0" {
Expand Down
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 @@ -252,12 +251,7 @@ func runSubmit(cfg config.Config, flags *pflag.FlagSet, args []string) error {
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 decodedAPIErrorResponse(resp)
}

bb := &bytes.Buffer{}
Expand All @@ -283,10 +277,3 @@ func runSubmit(cfg config.Config, flags *pflag.FlagSet, args []string) 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 f0f6424

Please sign in to comment.