flutter 如何在linkException中捕获parsedResponse?

gc0ot86w  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(138)

在上面的错误中,我试图获取parsedResponse并为statusCode添加处理,但我无法捕获错误。
linkException似乎无法识别parsedResponse。如果你知道一个解决方案,请让我知道。
谢谢
下面是我使用graphql_flutter制作和使用的graphql客户端

import 'package:firebase_auth/firebase_auth.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
// ignore: implementation_imports
import 'package:gql/src/ast/ast.dart';
import 'package:noling_app/config/parser.dart';

class MyGraphQLClient {
  late GraphQLClient _client;
  GraphQLClient get client => _client;

  GraphQLClient setClient(String idToken) {
    HttpLink _httpLink = HttpLink(
      'http://localhost:5005/noling-develop/asia-northeast3/graphql',
      parser: CustomResponseParser(),
      defaultHeaders: {
        'X-USER-TOKEN': idToken,
      },
    );
    Link _link;
    if (idToken != '' && idToken.isNotEmpty) {
      final AuthLink authLink = AuthLink(
        getToken: () => idToken,
        headerKey: 'X-USER-TOKEN',
      );
      _link = authLink.concat(_httpLink);
    } else {
      _link = _httpLink;
    }

    _client = GraphQLClient(
      cache: GraphQLCache(),
      link: _link,
    );

    return _client;
  }

  Future<dynamic> query(
    DocumentNode document, {
    Map<String, dynamic>? data,
  }) async {
    try {
      QueryResult result = await _client.query(QueryOptions(
        document: document,
        variables: data ?? {},
      ));

      if (result.hasException) {
        print(result);
        var message = result.exception!.graphqlErrors.first.message;
        throw Exception(message);
      }

      return result.data;
    } catch (e) {
      print("error catch ?");
      rethrow;
    }
  }

  Future<dynamic> mutate(
    DocumentNode document, {
    Map<String, dynamic>? data,
  }) async {
    var result = await _client.mutate(MutationOptions(
      document: document,
      variables: data ?? {},
    ));

    if (result.hasException) {
      var message = result.exception!.graphqlErrors.first.message;
      throw GraphQLError(message: message);
    }

    return result.data;
  }
}

MyGraphQLClient graphQLClient = MyGraphQLClient();

在MyGraphQLClient类中,我创建并使用了一个CustomResponseParser,就像我在另一个问题帖子中看到的那样,但没有用。

class CustomResponseParser extends ResponseParser {
  @override
  Response parseResponse(Map<String, dynamic> body) {
    Map<String, String> errors = new Map();
    if (body["errors"] != null) {
      errors['message'] = body["errors"][0];
    }
    Response res = Response(
      response: body,
      errors: (body["errors"] as List?)
          ?.map(
            (dynamic error) => parseError(errors),
          )
          .toList(),
      data: body["data"] as Map<String, dynamic>?,
      context: const Context().withEntry(
        ResponseExtensions(
          body["extensions"],
        ),
      ),
    );

    print(res);

    return res;
  }

  @override
  GraphQLError parseError(Map<String, dynamic> error) {
    return GraphQLError(
      message: error['message'],
    );
  }
}
jaxagkaj

jaxagkaj1#

看起来如果你先将result.exception.linkException转换为ServerException,你就可以访问parsedResponse
示例:

if(result.exception?.linkException != null)
  String? errorMessage = (result.exception!.linkException as ServerException).parsedResponse?.errors?.first.message;

信用去找到这里的解决方案(链接编辑):Unable to retrieve errors occured in Graphql mutation in flutter project
--感谢@DavidW的链接更正

相关问题