我正在使用 Dio 来处理 API 函数。
这是我的代码:
Future<List<ItemModel>> getItems() async {
try {
Response response = await dio.get("$_apiUrl$_itemEndPoint",
options: Options(headers: {
"Accept": 'application/json',
}));
List<ItemModel> _items = List<ItemModel>();
response.data['data']?.forEach((c) {
_items.add(ItemModel.fromMap(c));
});
return _items;
} catch (e) {
throw (e);
}
}
如何根据发送和接收超时捕获错误?
使用 dio 管理超时异常:
ApiRepositary.dart
class ApiRepositary {
Dio dio;
ApiRepositary() {
if (dio == null) {
BaseOptions options = new BaseOptions(
baseUrl: "your base url",
receiveDataWhenStatusError: true,
connectTimeout: 60*1000, // 60 seconds
receiveTimeout: 60*1000 // 60 seconds
);
dio = new Dio(options);
}
}
Future<LoginResponse> getLoginDetails(var loginRequestData) async {
try {
Response response = await dio.post("/authenticate", data: loginRequestData);
final LoginResponse loginResponse = LoginResponse.fromJson(response.data);
return loginResponse;
}on DioError catch (ex) {
if(ex.type == DioErrorType.CONNECT_TIMEOUT){
throw Exception("Connection Timeout Exception");
}
throw Exception(ex.message);
}
}
}
处理异常示例:
void checkLogin(){
LoginRequest loginRequest = new LoginRequest(
email: "[email protected]",password: "passs@123");
var requestBody =jsonEncode(loginRequest);
debugPrint("Request Data : $requestBody");
_apiRepositary.getLoginDetails(requestBody).then((response){
debugPrint("Login Success $response");
//manage your response here
},
onError: (exception){
//Handle exception message
if(exception.message != null ){
debugPrint(exception.message); // Here you get : "Connection Timeout Exception"
}
},
);
}
您首先要定义DIO选项:
BaseOptions options = new BaseOptions(
baseUrl: "http://example.org",
connectTimeout: 5000,
receiveTimeout: 3000,
);
然后:
Dio dio = new Dio(options);
var jsonNews = await dio.get(
'http://example.org/v2/everything?q=bitcoin&from=2020-01-24&sortBy=publishedAt&apiKey=7f3c604b6e2245c88se50lzx02dc9cac1e2');
来源:
您可以使用 try-catch 来处理超时异常并根据您的情况进行处理
你好,我是病毒啊哈哈哈哈哈哈