You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LinkException中捕获parsedResponse?附GraphQL-Flutter代码

问题描述

这是我遇到的错误弹窗

针对上述错误,我尝试获取parsedResponse并添加statusCode处理逻辑,但无法捕获该错误。LinkException似乎无法识别parsedResponse,恳请告知解决方案。

感谢帮助!

相关代码

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

自定义响应解析器

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'],
    );
  }
}

内容的提问来源于stack exchange,提问作者raonlast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:10:15