diff --git a/graphql.go b/graphql.go index 706092d..d72264f 100644 --- a/graphql.go +++ b/graphql.go @@ -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) @@ -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) diff --git a/graphql_test.go b/graphql_test.go index 224e926..544ac7d 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -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 != "" { @@ -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 {