Skip to content

Commit

Permalink
throw NetworkError when the server returns a non-200 http status (#143)
Browse files Browse the repository at this point in the history
* throw NetworkError when the server returns a non-200 http status
  • Loading branch information
LukeSparkLayer authored Jun 21, 2024
1 parent 4f88d35 commit fa97047
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
24 changes: 22 additions & 2 deletions graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,11 @@ func (c *Client) request(ctx context.Context, query string, variables map[string
}

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
err := newError(ErrRequestError, fmt.Errorf("%v; body: %q", resp.Status, body))
b, _ := io.ReadAll(resp.Body)
err := newError(ErrRequestError, NetworkError{
statusCode: resp.StatusCode,
body: string(b),
})

if c.debug {
err = err.withRequest(request, reqReader)
Expand Down Expand Up @@ -386,6 +389,23 @@ func newError(code string, err error) Error {
}
}

type NetworkError struct {
body string
statusCode int
}

func (e NetworkError) Error() string {
return fmt.Sprintf("%d %s", e.statusCode, http.StatusText(e.statusCode))
}

func (e NetworkError) Body() string {
return e.body
}

func (e NetworkError) StatusCode() int {
return e.statusCode
}

func (e Error) withRequest(req *http.Request, bodyReader io.Reader) Error {
internal := e.getInternalExtension()
bodyBytes, err := io.ReadAll(bodyReader)
Expand Down
4 changes: 2 additions & 2 deletions graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func TestClient_Query_errorStatusCode(t *testing.T) {
if err == nil {
t.Fatal("got error: nil, want: non-nil")
}
if got, want := err.Error(), `Message: 500 Internal Server Error; body: "important message\n", Locations: [], Extensions: map[code:request_error], Path: []`; got != want {
if got, want := err.Error(), `Message: 500 Internal Server Error, Locations: [], Extensions: map[code:request_error], Path: []`; got != want {
t.Errorf("got error: %v, want: %v", got, want)
}
if q.User.Name != "" {
Expand All @@ -240,7 +240,7 @@ func TestClient_Query_errorStatusCode(t *testing.T) {
t.Errorf("the error type should be graphql.Errors")
}
gqlErr = err.(graphql.Errors)
if got, want := gqlErr[0].Message, `500 Internal Server Error; body: "important message\n"`; got != want {
if got, want := gqlErr[0].Message, `500 Internal Server Error`; got != want {
t.Errorf("got error: %v, want: %v", got, want)
}
if got, want := gqlErr[0].Extensions["code"], graphql.ErrRequestError; got != want {
Expand Down

0 comments on commit fa97047

Please sign in to comment.