Skip to content

Commit

Permalink
Download response uses shared error parser
Browse files Browse the repository at this point in the history
  • Loading branch information
jdsutherland committed Mar 1, 2019
1 parent 448ce88 commit 8ebb29a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 22 deletions.
13 changes: 11 additions & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"strings"

"io"

Expand Down Expand Up @@ -78,14 +79,22 @@ func validateUserConfig(cfg *viper.Viper) error {
func decodedAPIError(resp *http.Response) error {
var apiError struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
Type string `json:"type"`
Message string `json:"message"`
PossibleTrackIDs []string `json:"possible_track_ids"`
} `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 != "" {
if apiError.Error.Type == "track_ambiguous" {
return fmt.Errorf(
"%s: %s",
apiError.Error.Message,
strings.Join(apiError.Error.PossibleTrackIDs, ", "),
)
}
return fmt.Errorf(apiError.Error.Message)
}
return fmt.Errorf("unexpected API response: %d", resp.StatusCode)
Expand Down
21 changes: 1 addition & 20 deletions cmd/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,26 +204,7 @@ func newDownload(flags *pflag.FlagSet, usrCfg *viper.Viper) (*download, error) {
defer res.Body.Close()

if err := json.NewDecoder(res.Body).Decode(&d.payload); err != nil {
return nil, fmt.Errorf("unable to parse API response - %s", err)
}

if res.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf(
"unauthorized request. Please run the configure command. You can find your API token at %s/my/settings",
config.InferSiteURL(d.apibaseurl),
)
}
if res.StatusCode != http.StatusOK {
switch d.payload.Error.Type {
case "track_ambiguous":
return nil, fmt.Errorf(
"%s: %s",
d.payload.Error.Message,
strings.Join(d.payload.Error.PossibleTrackIDs, ", "),
)
default:
return nil, errors.New(d.payload.Error.Message)
}
return nil, decodedAPIError(res)
}

return d, nil
Expand Down

0 comments on commit 8ebb29a

Please sign in to comment.