From 23f5662e7b4dc4ce9b46eb4c350b935c53ad4eca Mon Sep 17 00:00:00 2001 From: qzl Date: Wed, 25 Feb 2026 14:41:27 +0800 Subject: [PATCH] fix(apps): improve ApiInterceptor retry and error handling --- apps/lib/core/api/api_client.dart | 5 +++-- apps/lib/core/api/api_interceptor.dart | 13 ++++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/apps/lib/core/api/api_client.dart b/apps/lib/core/api/api_client.dart index d01f0d9..731cd62 100644 --- a/apps/lib/core/api/api_client.dart +++ b/apps/lib/core/api/api_client.dart @@ -19,6 +19,7 @@ class ApiClient { _dio.interceptors.add( ApiInterceptor( tokenStorage: _tokenStorage, + dio: _dio, onTokenRefresh: _handleTokenRefresh, ), ); @@ -40,7 +41,7 @@ class ApiClient { Future> get(String path, {Options? options}) async { try { return await _dio.get(path, options: options); - } catch (e) { + } on DioException catch (e) { throw ApiException.fromDioError(e); } } @@ -52,7 +53,7 @@ class ApiClient { }) async { try { return await _dio.post(path, data: data, options: options); - } catch (e) { + } on DioException catch (e) { throw ApiException.fromDioError(e); } } diff --git a/apps/lib/core/api/api_interceptor.dart b/apps/lib/core/api/api_interceptor.dart index 74550fe..a2db41c 100644 --- a/apps/lib/core/api/api_interceptor.dart +++ b/apps/lib/core/api/api_interceptor.dart @@ -4,8 +4,13 @@ import '../storage/token_storage.dart'; class ApiInterceptor extends Interceptor { final TokenStorage tokenStorage; final Future Function()? onTokenRefresh; + final Dio dio; - ApiInterceptor({required this.tokenStorage, this.onTokenRefresh}); + ApiInterceptor({ + required this.tokenStorage, + required this.dio, + this.onTokenRefresh, + }); @override void onRequest( @@ -28,10 +33,12 @@ class ApiInterceptor extends Interceptor { if (token != null) { err.requestOptions.headers['Authorization'] = 'Bearer $token'; try { - final response = await Dio().fetch(err.requestOptions); + final response = await dio.fetch(err.requestOptions); handler.resolve(response); return; - } catch (_) {} + } on DioException { + // Retry failed, proceed with original error + } } } }