diff --git a/dio/CHANGELOG.md b/dio/CHANGELOG.md index f0f58484b..f2d99c5b4 100644 --- a/dio/CHANGELOG.md +++ b/dio/CHANGELOG.md @@ -12,6 +12,8 @@ See the [Migration Guide][] for the complete breaking changes list.** - Split the Web implementation to `package:dio_web_adapter`. - Add FusedTransformer for improved performance when decoding JSON. - Improves `InterceptorState.toString()`. +- If the `CancelToken` got canceled before making requests, + throws the exception directly rather than cut actual HTTP requests afterward. ## 5.4.3+1 diff --git a/dio/lib/src/dio_mixin.dart b/dio/lib/src/dio_mixin.dart index a4aad5abb..4df2e7dbf 100644 --- a/dio/lib/src/dio_mixin.dart +++ b/dio/lib/src/dio_mixin.dart @@ -337,7 +337,11 @@ abstract class DioMixin implements Dio { Options? options, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, - }) { + }) async { + if (cancelToken != null && cancelToken.isCancelled) { + throw cancelToken.cancelError!; + } + final requestOptions = (options ?? Options()).compose( this.options, path, diff --git a/dio/test/cancel_token_test.dart b/dio/test/cancel_token_test.dart index 347a4492c..75f416e7e 100644 --- a/dio/test/cancel_token_test.dart +++ b/dio/test/cancel_token_test.dart @@ -87,5 +87,29 @@ void main() { verify(request.abort()).called(1); } }); + + test('throws if cancelled before making requests', () async { + final cancelToken = CancelToken(); + + bool walkThroughHandlers = false; + final interceptor = QueuedInterceptorsWrapper( + onRequest: (options, handler) { + walkThroughHandlers = true; + handler.next(options); + }, + ); + + cancelToken.cancel(); + final dio = Dio(); + dio.interceptors.add(interceptor); + await expectLater( + () => dio.get('/test', cancelToken: cancelToken), + throwsDioException( + DioExceptionType.cancel, + matcher: isA(), + ), + ); + expect(walkThroughHandlers, isFalse); + }); }); }