From 878c0ce459c3c51cc458e45769362b3bf00a7c19 Mon Sep 17 00:00:00 2001 From: Jorge Sevilla Date: Mon, 25 Jun 2018 18:22:19 +0200 Subject: [PATCH 1/2] Report more details about errors in do function Move status code control to the end of the 'do' function, so we can return more details about the error. --- graphql.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/graphql.go b/graphql.go index f2c5b54..55e443b 100644 --- a/graphql.go +++ b/graphql.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "io/ioutil" "net/http" "github.com/shurcooL/go/ctxhttp" @@ -69,9 +70,7 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab return err } defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("unexpected status: %v", resp.Status) - } + var out struct { Data *json.RawMessage Errors errors @@ -79,17 +78,28 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab } err = json.NewDecoder(resp.Body).Decode(&out) if err != nil { - return err + respBodyCopy, errRead := ioutil.ReadAll(resp.Body) + if errRead != nil { + fmt.Errorf("error decoding output: ", errRead) + } + return fmt.Errorf("error decoding output: %v (output was: %s)", err, respBodyCopy) } if out.Data != nil { err := jsonutil.UnmarshalGraphQL(*out.Data, v) if err != nil { - return err + return fmt.Errorf("error unmarshalling data: %s", err) } } if len(out.Errors) > 0 { return out.Errors } + if resp.StatusCode != http.StatusOK { + respBodyCopy, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Errorf("unexpected status: %v ", resp.Status, err) + } + return fmt.Errorf("unexpected status: %v %s", resp.Status, respBodyCopy) + } return nil } From 605c8161d017b7a8976d474ca02f8bada4ebdfe7 Mon Sep 17 00:00:00 2001 From: Jorge Sevilla Date: Mon, 25 Jun 2018 18:31:06 +0200 Subject: [PATCH 2/2] Return ignored Errorf errors --- graphql.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphql.go b/graphql.go index 55e443b..839d14f 100644 --- a/graphql.go +++ b/graphql.go @@ -80,7 +80,7 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab if err != nil { respBodyCopy, errRead := ioutil.ReadAll(resp.Body) if errRead != nil { - fmt.Errorf("error decoding output: ", errRead) + return fmt.Errorf("error decoding output: ", errRead) } return fmt.Errorf("error decoding output: %v (output was: %s)", err, respBodyCopy) } @@ -96,7 +96,7 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab if resp.StatusCode != http.StatusOK { respBodyCopy, err := ioutil.ReadAll(resp.Body) if err != nil { - fmt.Errorf("unexpected status: %v ", resp.Status, err) + return fmt.Errorf("unexpected status: %v ", resp.Status, err) } return fmt.Errorf("unexpected status: %v %s", resp.Status, respBodyCopy) }