Skip to content

Commit 6288dcd

Browse files
committed
Don't attempt to decode potentially invalid JSON
1 parent 5481fbd commit 6288dcd

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

client.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"bytes"
1414
"encoding/json"
1515
"errors"
16+
"fmt"
1617
"io/ioutil"
1718
"log"
1819
"net/http"
@@ -119,17 +120,20 @@ func (c *Client) Request(v interface{}, method, path string, data interface{}) e
119120
if response.StatusCode == 500 {
120121
return ErrUnexpectedResponse
121122
}
122-
123-
if err = json.Unmarshal(responseBody, &v); err != nil {
124-
return err
125-
}
126-
127123
// Status codes 200 and 201 are indicative of being able to convert the
128124
// response body to the struct that was specified.
129125
if response.StatusCode == 200 || response.StatusCode == 201 {
126+
if err := json.Unmarshal(responseBody, &v); err != nil {
127+
return fmt.Errorf("could not decode response JSON, %s: %v", string(responseBody), err)
128+
}
130129
return nil
131130
}
132131

132+
// We're dealing with an API error here. try to decode it, but don't do
133+
// anything with the error. This is because not all values of `v` have
134+
// `Error` properties and decoding could fail.
135+
json.Unmarshal(responseBody, &v)
136+
133137
// Anything else than a 200/201/500 should be a JSON error.
134138
return ErrResponse
135139
}

0 commit comments

Comments
 (0)