我正在使用以下代码成功轮询 mysite 以获取 JSON 数据并返回该数据。如果请求失败,那么它也成功返回错误消息return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);
。
我想要发生的是让应用程序在返回错误消息之前重试请求 3 次。
基本上有一些迭代次数的未来调用本身。
我确实尝试创建一个外部函数,该函数将从外部 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);
}
}
在里面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);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句