MST

星途 面试题库

面试题:Flutter dio插件复杂网络请求的异常处理与重试机制

在Flutter应用里,使用dio插件进行复杂网络请求时,可能会遇到网络波动、服务器响应超时等异常情况。请描述如何优雅地处理这些异常,并实现一个简单的重试机制,当请求失败时能自动重试一定次数,详细说明设计思路和实现代码。
13.1万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 异常捕获:使用try-catch块捕获Dio请求过程中可能抛出的异常,如网络波动导致的DioErrorType.connectionError、服务器响应超时导致的DioErrorType.connectTimeoutDioErrorType.receiveTimeout等。
  2. 重试机制:设定最大重试次数,当捕获到异常时,判断是否达到最大重试次数,如果未达到则进行重试,达到则抛出最终异常。

实现代码

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