Skip to content

Commit 5d5bd04

Browse files
committed
💅 Extract parsing error response into its own function
1 parent d57b517 commit 5d5bd04

File tree

1 file changed

+32
-22
lines changed

1 file changed

+32
-22
lines changed

pkg/cmd/api/api.go

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -118,31 +118,10 @@ func apiRun(opts *ApiOptions) error {
118118

119119
var serverError string
120120
if isJSON && (opts.RequestPath == "graphql" || resp.StatusCode >= 400) {
121-
bodyCopy := &bytes.Buffer{}
122-
b, err := ioutil.ReadAll(io.TeeReader(responseBody, bodyCopy))
121+
responseBody, serverError, err = parseErrorResponse(responseBody, resp.StatusCode)
123122
if err != nil {
124123
return err
125124
}
126-
var respData struct {
127-
Message string
128-
Errors []struct {
129-
Message string
130-
}
131-
}
132-
err = json.Unmarshal(b, &respData)
133-
if err != nil {
134-
return err
135-
}
136-
if respData.Message != "" {
137-
serverError = fmt.Sprintf("%s (HTTP %d)", respData.Message, resp.StatusCode)
138-
} else if len(respData.Errors) > 0 {
139-
msgs := make([]string, len(respData.Errors))
140-
for i, e := range respData.Errors {
141-
msgs[i] = e.Message
142-
}
143-
serverError = strings.Join(msgs, "\n")
144-
}
145-
responseBody = bodyCopy
146125
}
147126

148127
if isJSON && opts.IO.ColorEnabled() {
@@ -234,3 +213,34 @@ func readUserFile(fn string, stdin io.ReadCloser) ([]byte, error) {
234213
defer r.Close()
235214
return ioutil.ReadAll(r)
236215
}
216+
217+
func parseErrorResponse(r io.Reader, statusCode int) (io.Reader, string, error) {
218+
bodyCopy := &bytes.Buffer{}
219+
b, err := ioutil.ReadAll(io.TeeReader(r, bodyCopy))
220+
if err != nil {
221+
return r, "", err
222+
}
223+
224+
var parsedBody struct {
225+
Message string
226+
Errors []struct {
227+
Message string
228+
}
229+
}
230+
err = json.Unmarshal(b, &parsedBody)
231+
if err != nil {
232+
return r, "", err
233+
}
234+
235+
if parsedBody.Message != "" {
236+
return bodyCopy, fmt.Sprintf("%s (HTTP %d)", parsedBody.Message, statusCode), nil
237+
} else if len(parsedBody.Errors) > 0 {
238+
msgs := make([]string, len(parsedBody.Errors))
239+
for i, e := range parsedBody.Errors {
240+
msgs[i] = e.Message
241+
}
242+
return bodyCopy, strings.Join(msgs, "\n"), nil
243+
}
244+
245+
return bodyCopy, "", nil
246+
}

0 commit comments

Comments
 (0)