From 038f502da0026f7e4d3ab30fd4b1a08dea10e330 Mon Sep 17 00:00:00 2001 From: Cara Wang Date: Fri, 17 Feb 2023 17:21:38 +0800 Subject: [PATCH] graphql: can parse error from graphql server --- graphql.go | 10 ++++++---- graphql_json_test.go | 6 +++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/graphql.go b/graphql.go index f98b674..c19ca29 100644 --- a/graphql.go +++ b/graphql.go @@ -311,17 +311,19 @@ func ImmediatelyCloseReqBody() ClientOption { // modify the behaviour of the Client. type ClientOption func(*Client) -type graphErr struct { - Message string +type GraphQLErr struct { + Message string `json:"message"` + Path []interface{} `json:"path,omitempty"` + Extensions map[string]interface{} `json:"extensions,omitempty"` } -func (e graphErr) Error() string { +func (e GraphQLErr) Error() string { return "graphql: " + e.Message } type graphResponse struct { Data interface{} - Errors []graphErr + Errors []GraphQLErr } // Request is a GraphQL request. diff --git a/graphql_json_test.go b/graphql_json_test.go index a973d2d..515c012 100644 --- a/graphql_json_test.go +++ b/graphql_json_test.go @@ -78,7 +78,9 @@ func TestDoJSONBadRequestErr(t *testing.T) { w.WriteHeader(http.StatusBadRequest) io.WriteString(w, `{ "errors": [{ - "message": "miscellaneous message as to why the the request was bad" + "message": "miscellaneous message as to why the the request was bad", + "path": ["location"], + "extensions": {"code": "BAD_USER_INPUT", "subCode": 1063} }] }`) })) @@ -93,6 +95,8 @@ func TestDoJSONBadRequestErr(t *testing.T) { err := client.Run(ctx, &Request{q: "query {}"}, &responseData) is.Equal(calls, 1) // calls is.Equal(err.Error(), "graphql: miscellaneous message as to why the the request was bad") + is.Equal(err.(GraphQLErr).Path[0], "location") + is.Equal(err.(GraphQLErr).Extensions["code"], "BAD_USER_INPUT") } func TestQueryJSON(t *testing.T) {