Skip to content

Commit

Permalink
fix: handle spotify not 200 (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgeGorbanev authored Sep 1, 2024
1 parent de37bd0 commit f6b74b8
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
17 changes: 17 additions & 0 deletions internal/spotify/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ type albumsSection struct {
Items []*Album `json:"items"`
}

type apiError struct {
Status int `json:"status"`
Message string `json:"message"`
}

type errorResponse struct {
Error apiError `json:"error"`
}

func NewHTTPClient(credentials *Credentials, opts ...ClientOption) *HTTPClient {
c := HTTPClient{
authURL: defaultAuthURL,
Expand Down Expand Up @@ -174,6 +183,14 @@ func (c *HTTPClient) getAPI(ctx context.Context, path string, query url.Values)
return nil, fmt.Errorf("failed to read response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
er := errorResponse{}
if err := json.Unmarshal(body, &er); err != nil {
return nil, fmt.Errorf("failed to load error response")
}
return nil, fmt.Errorf("unexpected API response: %d %s", er.Error.Status, er.Error.Message)
}

return body, nil
}

Expand Down
36 changes: 36 additions & 0 deletions internal/spotify/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,42 @@ func TestHTTPClient_RefreshTokenWhenUnauthorized(t *testing.T) {
}, track)
}

func TestHTTPClient_APIError(t *testing.T) {
mockAuthServer := newAuthServerMock(t)
defer mockAuthServer.Close()

mockAPIServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodGet, r.Method)

authorization := r.Header.Get("Authorization")
require.Equal(t, authorization, "Bearer mock_access_token")
require.Equal(t, r.URL.Path, "/v1/tracks/sampletrackid")
w.WriteHeader(http.StatusForbidden)
_, err := w.Write([]byte(`{
"error" : {
"status" : 403,
"message" : "Spotify is unavailable in this country"
}
}`))
require.NoError(t, err)
}))
defer mockAPIServer.Close()

client := NewHTTPClient(
&sampleCredentials,
WithAuthURL(mockAuthServer.URL),
WithAPIURL(mockAPIServer.URL),
)

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

track, err := client.FetchTrack(ctx, "sampletrackid")
require.Errorf(t, err,
"failed to send request: unexpected API response: 403 Spotify is unavailable in this country")
require.Nil(t, track)
}

func newAuthServerMock(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodPost, r.Method)
Expand Down

0 comments on commit f6b74b8

Please sign in to comment.