面试题答案
一键面试设计思路
- 异常捕获:使用
try-catch
块捕获Dio
请求过程中可能抛出的异常,如网络波动导致的DioErrorType.connectionError
、服务器响应超时导致的DioErrorType.connectTimeout
和DioErrorType.receiveTimeout
等。 - 重试机制:设定最大重试次数,当捕获到异常时,判断是否达到最大重试次数,如果未达到则进行重试,达到则抛出最终异常。
实现代码
import 'package:dio/dio.dart';
class RetryDio {
final Dio dio;
final int maxRetries;
RetryDio({required this.dio, required this.maxRetries});
Future<Response> retryRequest(RequestOptions options) async {
int retryCount = 0;
while (retryCount < maxRetries) {
try {
return await dio.request(options.path,
data: options.data,
queryParameters: options.queryParameters,
options: options);
} on DioError catch (e) {
if (e.type == DioErrorType.connectionError ||
e.type == DioErrorType.connectTimeout ||
e.type == DioErrorType.receiveTimeout) {
retryCount++;
if (retryCount >= maxRetries) {
throw e;
}
print('Retry attempt $retryCount due to: ${e.message}');
} else {
throw e;
}
}
}
throw Exception('Max retry attempts reached');
}
}
使用示例:
void main() async {
Dio dio = Dio();
RetryDio retryDio = RetryDio(dio: dio, maxRetries: 3);
try {
Response response = await retryDio.retryRequest(RequestOptions(path: 'your_api_url'));
print(response.data);
} catch (e) {
print('Final error: $e');
}
}