简体   繁体   中英

Unable to retrieve errors occured in Graphql mutation in flutter project

I am using the package graphql_flutter for GraphQL operations in my flutter app. The queries and mutations are going well but I cannot retrieve the errors by following the ways mentioned in their doc. Every time I receive a generic error message which is,

ClientException: Failed to connect to http://127.0.0.1:3006/graphql: 

That I get by doing,

print(result.exception.toString());

My mutation looks like,

final MutationOptions mutationOptions = MutationOptions(
  documentNode: gql(mutationString),
  variables: vars
);

final QueryResult result = await _instance._client.mutate(mutationOptions);

if (result.hasException) {
  // none of the following prints the expected error.
  print(result.exception.clientException.message);
  print(result.exception.graphqlErrors);
  print(result.exception.toString());
}

print(result.data);

return result.data;

Whereas in the apollo client, My error is:

{
  "errors": [
    {
      "message": "Invalid Phone number provided",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "otp"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
         ....

But I get none of that.

Note: The success response is coming as expected. I would like to know how can I get the graphql errors.

I found the problem. It is because android cannot connect to 127.0.0.1 or localhost from the emulator. I replaced the host with my local IP address and it is working fine now.

Put this in a try/ catch block and see if it can catch any exceptions

final QueryResult result = await _instance._client.mutate(mutationOptions);

the original question was how to get the graphql errors. I'm using graphql: ^5.0.0

I checked the docs and found this example:

if (result.hasException) {
  if (result.exception.linkException is NetworkException) {
     // handle network issues, maybe
    }
   return Text(result.exception.toString())
 }

but that just gave me the exception, not the error, I casted the result exception to the type of error and was able to get the message:

if (result.hasException) {
    if (result.exception!.linkException is ServerException) {
      ServerException exception =
          result.exception!.linkException as ServerException;
      var errorMessage = exception.parsedResponse!.errors![0].message;
      print(errorMessage);
      throw Exception(errorMessage);
    }
  } 

this seems like a lot of work for a simple message, I wonder if there is another simpler built-in way to do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM