From 3e23dcab1598176049a54c57ce85f5a770a1c685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 18 Aug 2021 22:17:32 +0200 Subject: [PATCH] Fix HTTP 502 error reporting from GraphQL request Now it makes sure that the message portion will be printed to stderr when the user encounters the error. --- api/client.go | 7 +++++-- api/client_test.go | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/api/client.go b/api/client.go index 196c65692..c11a7f7ed 100644 --- a/api/client.go +++ b/api/client.go @@ -285,7 +285,10 @@ func HandleHTTPError(resp *http.Response) error { return httpError } - messages := []string{parsedBody.Message} + var messages []string + if parsedBody.Message != "" { + messages = append(messages, parsedBody.Message) + } for _, raw := range parsedBody.Errors { switch raw[0] { case '"': @@ -297,7 +300,7 @@ func HandleHTTPError(resp *http.Response) error { var errInfo HTTPErrorItem _ = json.Unmarshal(raw, &errInfo) msg := errInfo.Message - if errInfo.Code != "custom" { + if errInfo.Code != "" && errInfo.Code != "custom" { msg = fmt.Sprintf("%s.%s %s", errInfo.Resource, errInfo.Field, errorCodeToMessage(errInfo.Code)) } if msg != "" { diff --git a/api/client_test.go b/api/client_test.go index df0fdf8e2..fae0350b6 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -129,3 +129,20 @@ func TestRESTError(t *testing.T) { } } + +func TestHandleHTTPError_GraphQL502(t *testing.T) { + req, err := http.NewRequest("GET", "https://api.github.com/user", nil) + if err != nil { + t.Fatal(err) + } + resp := &http.Response{ + Request: req, + StatusCode: 502, + Body: ioutil.NopCloser(bytes.NewBufferString(`{ "data": null, "errors": [{ "message": "Something went wrong" }] }`)), + Header: map[string][]string{"Content-Type": {"application/json"}}, + } + err = HandleHTTPError(resp) + if err == nil || err.Error() != "HTTP 502: Something went wrong (https://api.github.com/user)" { + t.Errorf("got error: %v", err) + } +}