Uh oh!
There was an error while loading. Please reload this page.
Do response code checks earlier - #47
Conversation
| if err != nil { | ||
| return err | ||
| } | ||
| if res.StatusCode != http.StatusOK { |
There was a problem hiding this comment.
This should come after defer res.Body.Close(). As mentioned in the http.Client.Do docs:
If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close.
Similar below.
necrophonic
commented
Oct 21, 2019
Is there any chance we could return the response from the server, potentially as part of the error, if there was one? In your case above (and actually the exact issue I'm having!) it would be helpful to have the message from the server as well as the status code error. |
saopayne
commented
Jan 15, 2020
When can we have this in a release, please? Line 142 in 3a92531 We need this check and it's not available in V2.2. Can master be promoted to a release? |
marwan-at-work
commented
Feb 6, 2020
I think it would be great if we used Go 1.13 primitives to return a friendly error response while still being able to get the un-modified response body and status code from the user side, something like this: typeStatusErrorstruct {
CodeintBody []byte
}
func (se*StatusError) Error() string {
returnfmt.Sprintf("unexpected response code: %d", se.Code)
}
// later onifresp.StatusCode!=200 {
body, _:=ioutil.ReadAll(resp.Body)
return&StatusError{Code: resp.StatusCode, Body: body}
}This way, a user can see a nicely formatted error but also be able to inspect both the code and the body by doing the following: import"errors"varstatusErr*graphql.StatusErroriferrors.As(&statusErr) {
json.Unmarshal(statusErr.Body, &myCustomStruct) // etc etc
}Just FYI, users of Go version 1.12 and lower can still leverage the code above by just type-casting the error value. |
sminf
commented
May 8, 2020
According to @marwan-at-work's proposal, I wrote a GraphQL client for better error handling. |
JanDonnermayer
commented
Jun 21, 2020
Thx! This client is much better, yet better documented |
cheshire137
commented
Dec 6, 2022
I found this PR still lingering, I'm going to close it out as stale. Thanks all! |
matryer
commented
Dec 6, 2022
via email
Sorry about this. We lost control of the repo, so it’s forked at https://github.com/matryer/graphql which we can control. |
karelbilek
commented
Jun 13, 2024
Who can control the repo? It should be more clearly stated that it's unmaintained |
This builds on @erutherford's change in #19 by moving the status code checks earlier. The library was only checking the response code if there was a problem decoding the response body as JSON, but a non-200 response from the API indicates a problem even if the response body was valid JSON. For example, the GitHub GraphQL API will return the valid JSON
{"message":"Bad credentials","documentation_url":"https://developer.github.com/v4"}if you give bad credentials.cc @matryer 🙇♀