Merge pull request #1494 from mmontes11/generalize-gql-error-parsing

Generalize REST error parsing
This commit is contained in:
Mislav Marohnić 2020-08-10 16:30:45 +02:00 committed by GitHub
commit 23337e0b07
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 9 deletions

View file

@ -426,23 +426,43 @@ func parseErrorResponse(r io.Reader, statusCode int) (io.Reader, string, error)
var parsedBody struct {
Message string
Errors []struct {
Message string
}
Errors []json.RawMessage
}
err = json.Unmarshal(b, &parsedBody)
if err != nil {
return r, "", err
}
if parsedBody.Message != "" {
return bodyCopy, fmt.Sprintf("%s (HTTP %d)", parsedBody.Message, statusCode), nil
} else if len(parsedBody.Errors) > 0 {
msgs := make([]string, len(parsedBody.Errors))
for i, e := range parsedBody.Errors {
msgs[i] = e.Message
}
type errorMessage struct {
Message string
}
var errors []string
for _, rawErr := range parsedBody.Errors {
if len(rawErr) == 0 {
continue
}
return bodyCopy, strings.Join(msgs, "\n"), nil
if rawErr[0] == '{' {
var objectError errorMessage
err := json.Unmarshal(rawErr, &objectError)
if err != nil {
return r, "", err
}
errors = append(errors, objectError.Message)
} else if rawErr[0] == '"' {
var stringError string
err := json.Unmarshal(rawErr, &stringError)
if err != nil {
return r, "", err
}
errors = append(errors, stringError)
}
}
if len(errors) > 0 {
return bodyCopy, strings.Join(errors, "\n"), nil
}
return bodyCopy, "", nil

View file

@ -264,6 +264,17 @@ func Test_apiRun(t *testing.T) {
stdout: `{"message": "THIS IS FINE"}`,
stderr: "gh: THIS IS FINE (HTTP 400)\n",
},
{
name: "REST string errors",
httpResponse: &http.Response{
StatusCode: 400,
Body: ioutil.NopCloser(bytes.NewBufferString(`{"errors": ["ALSO", "FINE"]}`)),
Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}},
},
err: cmdutil.SilentError,
stdout: `{"errors": ["ALSO", "FINE"]}`,
stderr: "gh: ALSO\nFINE\n",
},
{
name: "GraphQL error",
options: ApiOptions{