无法检索 flutter 项目中 Graphql 突变中发生的错误

Unable to retrieve errors occured in Graphql mutation in flutter project

我在我的 flutter 应用程序中使用包 graphql_flutter 进行 GraphQL 操作。查询和突变进展顺利,但我无法按照他们的文档中提到的方式检索错误。每次我收到一条通用错误消息时,

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

我靠做,

print(result.exception.toString());

我的突变看起来像,

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;

而在 apollo 客户端中,我的错误是:

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

但我得到了 none。

注意:成功响应如期而至。我想知道如何获取 graphql 错误。

将其放入 try/catch 块中,看看它是否可以捕获任何异常

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

我发现了问题。这是因为 android 无法从模拟器连接到 127.0.0.1localhost。我用我的本地 IP 地址替换了主机,现在它工作正常。

最初的问题是如何获取 graphql 错误。 我正在使用 graphql:^5.0.0

我查看了文档并找到了这个示例:

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

但这只是给了我异常,而不是错误,我将结果异常转换为错误类型并且能够得到消息:

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);
    }
  } 

对于一条简单的消息来说,这似乎需要很多工作,我想知道是否有另一种更简单的内置方法可以做到这一点