如果 Flutter 中失败,Future 可以在内部重试 http 请求吗?

Mar*_*ark 5 dart flutter

我使用以下代码成功轮询 mysite 以获取 JSON 数据并返回该数据。如果请求失败,那么它也会成功返回一条错误消息return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);

我希望发生的是让应用程序在返回错误消息之前重试请求 3 次。

基本上让 future 调用自己进行一定次数的迭代。

我确实尝试创建一个外部函数,该函数将从外部 catch 调用,然后依次调用 getJSONfromTheSite 函数,然后第三次,但问题是您将从 Future 获得非空返回,因此该应用程序不会接受这种方法

还有另一种方法可以做到这一点吗?

          Future<Result> getJSONfromTheSite(String call) async {
            debugPrint('Network Attempt by getJSONfromTheSite');
            try {

              final response = await http.get(Uri.parse('http://www.thesite.com/'));

              if (response.statusCode == 200) {
                return Result<AppData>.success(AppData.fromRawJson(response.body));
              } else {
                //return Result.error("Error","Status code not 200", 1);
                return Result.error(title:"Error",msg:"Status code not 200", errorcode:1);
              }
            } catch (error) {
                return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);
            }
          }
Run Code Online (Sandbox Code Playgroud)

nvo*_*igt 6

以下扩展方法将采用 future 工厂,创建它们并尝试它们,直到达到重试限制:

extension Retry<T> on Future<T> Function() {
  Future<T> withRetries(int count) async {
    while(true) {
      try {
        final future = this();
        return await future;
      } 
      catch (e) {
        if(count > 0) {
          count--;
        }
        else {
          rethrow;
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

假设你有一个相当简单的 dart 方法:

 Future<AppData> getJSONfromTheSite(String call) async {
      final response = await http.get(Uri.parse('http://www.thesite.com/'));

      if (response.statusCode == 200) {
        return AppData.fromRawJson(response.body);
      } else {
        throw Exception('Error');
      }
  }
Run Code Online (Sandbox Code Playgroud)

您现在可以这样称呼它:

try {
  final result = (() => getJSONfromTheSite('call data')).withRetries(3);
  // succeeded at some point, "result" being the successful result
}
catch (e) {
  // failed 3 times, the last error is in "e"
}
Run Code Online (Sandbox Code Playgroud)

如果您没有成功或引发异常的简单方法,则必须调整重试方法才能知道何时出现错误。也许使用具有类型的功能更强大的包之一Either,这样您就可以确定返回值是否是错误。


Nel*_*ago 3

在里面catch()你可以计算你重试了多少次,如果计数器小于三,你返回相同的getJSONfromTheSite()函数,但带有求和计数器。如果连接持续失败try{}并且计数器大于三,它将返回错误。

Future<Result> getJSONfromTheSite(String call, {counter = 0}) async {
            debugPrint('Network Attempt by getJSONfromTheSite');
            try {
              String? body = await tryGet();
              if (body != null) {
                return Result<AppData>.success(AppData.fromRawJson(response.body));
              } else {
                //return Result.error("Error","Status code not 200", 1);
                return Result.error(title:"Error",msg:"Status code not 200", errorcode:1);
              }
            } catch (error) {
                if(counter < 3) {  
                  counter += 1;
                  return getJSONfromTheSite(call, counter: counter);
                } else {
                  return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);
                }
            }
          }
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2084 次

最近记录:

4 年,6 月 前