cfug/dio

Dio fetch can't catch error

Closed this issue · 1 comments

Package

dio

Version

5.5.0+1

Operating-System

Android, iOS

Adapter

Default Dio

Output of flutter doctor -v

[✓] Flutter (Channel stable, 3.22.2, on macOS 14.5 23F79 darwin-arm64, locale ko-KR)
    • Flutter version 3.22.2 on channel stable at /Users/swom/Flutter/SDK/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 761747bfc5 (6주 전), 2024-06-05 22:15:13 +0200
    • Engine revision edd8546116
    • Dart version 3.4.3
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/swom/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/swom/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11572160)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15F31d
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11572160)

[✓] VS Code (version 1.91.1)
    • VS Code at /Users/swom/Flutter/tools/Visual Studio Code.app/Contents
    • Flutter extension version 3.92.0

Dart Version

3.4.3

Steps to Reproduce

  1. Token expiration
  2. After receive a new token, retry the API (dio.fetch)
  3. The api throws an error but fails to catch it as DioException.

Expected Result

If an error occurs in the API retried through dio.fetch, it must catch it immediately.
If I set a delay, It catch sometime the error later.

Actual Result

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    int statusCode = err.response?.statusCode ?? 0;
    RequestOptions errorRequestOptions = err.requestOptions;

    debugPrint('BFDioAuthInterceptor - onError : $statusCode');

    if (statusCode == 401) {
      // Token Expired
      String newToken = await BFPreferences.shared.getAccessToken();

      try {
        RequestOptions errorNewOptions = errorRequestOptions;
        errorNewOptions.headers['Authorization'] = 'Bearer $newToken';

        final response = await dio.fetch(errorNewOptions);
        return handler.resolve(response);
      } on DioException catch (e) {
        return handler.reject(e);
      }
    }
    return handler.reject(err);
  }