From 2603cc870f62f3d842d56ad4295f266745addd0c Mon Sep 17 00:00:00 2001 From: clragon Date: Mon, 15 May 2023 05:09:44 +0200 Subject: [PATCH] Deprecate `DioError` in favor of `DioException` (#1803) ### New Pull Request Checklist - [x] I have read the [Documentation](https://pub.dev/documentation/dio/latest/) - [x] I have searched for a similar pull request in the [project](https://github.com/cfug/dio/pulls) and found none - [x] I have updated this branch with the latest `main` branch to avoid conflicts (via merge from master or rebase) - [x] I have added the required tests to prove the fix/feature I'm adding - [x] I have updated the documentation (if necessary) - [x] I have run the tests without failures - [x] I have updated the `CHANGELOG.md` in the corresponding package ### Additional context and info (if any) Fixes #1789. #### Quick Summary `DioError` is misnamed, as it is of type `Exception` and not `Error`. The fix for this is to rename `DioError` to `DioException` and provide a typedef alias for `DioError` that is marked deprecated. The typedef offers a grace period for migration and makes this a non-breaking change that can be introduced as soon as possible to notify users of the deprecation. This PR makes these changes. Its worth considering also offering extra help with migration to users, for example by providing a lint with an automatic fix that turns `DioError` into `DioException` and `DioErrorType` into `DioExceptionType`. Signed-off-by: clragon Co-authored-by: Alex Li --- dio/CHANGELOG.md | 12 ++- dio/README-ZH.md | 24 ++--- dio/README.md | 36 +++---- dio/lib/dio.dart | 2 +- dio/lib/src/adapters/browser_adapter.dart | 15 +-- dio/lib/src/adapters/io_adapter.dart | 16 ++-- dio/lib/src/cancel_token.dart | 15 +-- dio/lib/src/dio/dio_for_native.dart | 14 +-- .../{dio_error.dart => dio_exception.dart} | 95 ++++++++++--------- dio/lib/src/dio_mixin.dart | 25 ++--- dio/lib/src/interceptor.dart | 36 ++++--- dio/lib/src/interceptors/log.dart | 6 +- dio/lib/src/options.dart | 6 +- dio/test/basic_test.dart | 16 ++-- dio/test/cancel_token_test.dart | 6 +- dio/test/download_test.dart | 12 +-- dio/test/exception_test.dart | 22 ++--- dio/test/interceptor_test.dart | 51 +++++----- dio/test/options_test.dart | 4 +- dio/test/pinning_test.dart | 16 ++-- dio/test/readtimeout_test.dart | 18 ++-- dio/test/request_test.dart | 2 +- dio/test/stacktrace_test.dart | 76 +++++++-------- example/lib/certificate_pinning.dart | 2 +- example/lib/custom_cache_interceptor.dart | 2 +- example/lib/dio.dart | 2 +- example/lib/generic.dart | 2 +- example/lib/queued_interceptor_crsftoken.dart | 4 +- example/lib/request_interceptors.dart | 6 +- example/lib/response_interceptor.dart | 6 +- example/lib/transformer.dart | 2 +- plugins/cookie_manager/CHANGELOG.md | 17 ++-- .../cookie_manager/lib/src/cookie_mgr.dart | 12 ++- plugins/cookie_manager/pubspec.yaml | 4 +- plugins/http2_adapter/CHANGELOG.md | 2 +- .../lib/src/connection_manager_imp.dart | 10 +- plugins/http2_adapter/pubspec.yaml | 4 +- plugins/http2_adapter/test/pinning_test.dart | 4 +- plugins/native_dio_adapter/CHANGELOG.md | 2 +- plugins/native_dio_adapter/pubspec.yaml | 6 +- 40 files changed, 321 insertions(+), 291 deletions(-) rename dio/lib/src/{dio_error.dart => dio_exception.dart} (65%) diff --git a/dio/CHANGELOG.md b/dio/CHANGELOG.md index 82c23dd80..5afb4ecd4 100644 --- a/dio/CHANGELOG.md +++ b/dio/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - Make `LogInterceptor` prints in DEBUG mode (when the assertion is enabled) by default. +- Deprecate `DioError` in favor of `DioException`. - Fix `IOHttpClientAdapter.onHttpClientCreate` Repeated calls - `IOHttpClientAdapter.onHttpClientCreate` has been deprecated and is scheduled for removal in Dio 6.0.0 - Please use the replacement `IOHttpClientAdapter.createHttpClient` instead. @@ -85,7 +86,6 @@ - refactor timeout logic - use 'arraybuffer' instead of 'blob' for xhr requests in web platform - ## 4.0.4 - Fix fetching null data in a response @@ -157,7 +157,6 @@ the subsequent interceptors processing logic more finely (whether to skip them o 2. fix #851 3. fix #641 - ## 3.0.9 2020.2.24 - Add test cases @@ -211,9 +210,9 @@ the subsequent interceptors processing logic more finely (whether to skip them o - ~~Options.cookies~~ -- ~~Options.connectionTimeout~~ ;We should config connection timed out in `BaseOptions`. For keep-alive reasons, not every request requires a separate connection。 +- ~~Options.connectionTimeout~~ ;We should config connection timed out in `BaseOptions`. For keep-alive reasons, not every request requires a separate connection。 -- `Options.followRedirects`、`Options.maxRedirects`、`Response.redirects` don't make sense in Flutter Web,because redirection can be automatically handled by browsers. +- `Options.followRedirects`、`Options.maxRedirects`、`Response.redirects` don't make sense in Flutter Web,because redirection can be automatically handled by browsers. - ~~FormData.from~~,use `FormData.fromMap` instead. - Delete ~~Formdata.asBytes()~~、~~Formdata.asBytesAsync()~~ , use `Formdata.readAsBytes()` instead. - Delete ~~`UploadFileInfo`~~ class, `MultipartFile` instead. @@ -246,7 +245,6 @@ Add `deleteOnError` parameter to `downloadUri` - support flutter version>=1.8 (fix #357) - ## 2.1.8 - fix #354 #312 @@ -280,20 +278,24 @@ First Stable version for 2.x ## 2.0 **Refactor the Interceptors** + - Support add Multiple Interceptors. - Add Log Interceptor - Add CookieManager Interceptor **API** + - Support Uri - Support `queryParameters` for all request API - Modify the `get` API **Options** + - Separate Options to three class: Options、BaseOptions、RequestOptions - Add `queryParameters` and `cookies` for BaseOptions **Adapter** + - Abstract HttpClientAdapter layer. - Provide a DefaultHttpClientAdapter which make http requests by `dart:io:HttpClient` diff --git a/dio/README-ZH.md b/dio/README-ZH.md index cda9e0831..ced65c6a8 100644 --- a/dio/README-ZH.md +++ b/dio/README-ZH.md @@ -31,8 +31,8 @@ dio 是一个强大的 Dart HTTP 请求库,支持全局配置、Restful API、 * [日志拦截器](#日志拦截器) * [自定义拦截器](#自定义拦截器) * [错误处理](#错误处理) - * [DioError](#dioerror) - * [DioErrorType](#dioerrortype) + * [DioException](#dioexception) + * [DioExceptionType](#dioexceptiontype) * [使用 application/x-www-form-urlencoded 编码](#使用-applicationx-www-form-urlencoded-编码) * [发送 FormData](#发送-formdata) * [多文件上传](#多文件上传) @@ -406,7 +406,7 @@ dio.interceptors.add( // 如果你想终止请求并触发一个错误,你可以使用 `handler.reject(error)`。 return handler.next(response); }, - onError: (DioError e, ErrorInterceptorHandler handler) { + onError: (DioException e, ErrorInterceptorHandler handler) { // 如果你想完成请求并返回一些自定义数据,你可以使用 `handler.resolve(response)`。 return handler.next(e); }, @@ -432,7 +432,7 @@ class CustomInterceptors extends Interceptor { } @override - Future onError(DioError err, ErrorInterceptorHandler handler) async { + Future onError(DioException err, ErrorInterceptorHandler handler) async { print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}'); super.onError(err, handler); } @@ -445,7 +445,7 @@ class CustomInterceptors extends Interceptor { 如果你想完成请求/响应并返回自定义数据,你可以 resolve 一个 `Response` 对象 或返回 `handler.resolve(data)` 的结果。 如果你想终止(触发一个错误,上层 `catchError` 会被调用)一个请求/响应, -那么可以 reject 一个`DioError` 对象或返回 `handler.reject(errMsg)` 的结果。 +那么可以 reject 一个`DioException` 对象或返回 `handler.reject(errMsg)` 的结果。 ```dart dio.interceptors.add( @@ -496,13 +496,13 @@ dio.interceptors.add(LogInterceptor(responseBody: false)); // 不输出响应内 ## 错误处理 -当请求过程中发生错误时, Dio 会将 `Error/Exception` 包装成一个 `DioError`: +当请求过程中发生错误时, Dio 会将 `Error/Exception` 包装成一个 `DioException`: ```dart try { // 404 await dio.get('https://api.pub.dev/not-exist'); -} on DioError catch (e) { +} on DioException catch (e) { // The request was made and the server responded with a status code // that falls out of the range of 2xx and is also not 304. if (e.response != null) { @@ -517,7 +517,7 @@ try { } ``` -### DioError +### DioException ```dart /// 错误的请求对应的配置。 @@ -527,7 +527,7 @@ RequestOptions requestOptions; Response? response; /// 错误的类型。 -DioErrorType type; +DioExceptionType type; /// 实际错误的内容。 Object? error; @@ -539,9 +539,9 @@ StackTrace? stackTrace; String? message; ``` -### DioErrorType +### DioExceptionType -见 [源码](lib/src/dio_error.dart)。 +见 [源码](lib/src/dio_exception.dart)。 ## 使用 application/x-www-form-urlencoded 编码 @@ -821,7 +821,7 @@ void initAdapter() { ```dart final cancelToken = CancelToken(); -dio.get(url, cancelToken: cancelToken).catchError((DioError err) { +dio.get(url, cancelToken: cancelToken).catchError((DioException err) { if (CancelToken.isCancel(err)) { print('Request canceled: ${err.message}'); } else { diff --git a/dio/README.md b/dio/README.md index 05a8247a5..2745fb16e 100644 --- a/dio/README.md +++ b/dio/README.md @@ -32,8 +32,8 @@ timeout, and custom adapters etc. * [LogInterceptor](#loginterceptor) * [Custom Interceptor](#custom-interceptor) * [Handling Errors](#handling-errors) - * [DioError](#dioerror) - * [DioErrorType](#dioerrortype) + * [DioException](#dioexception) + * [DioExceptionType](#dioexceptiontype) * [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) * [Sending FormData](#sending-formdata) * [Multiple files upload](#multiple-files-upload) @@ -304,7 +304,7 @@ Map? headers; Duration? connectTimeout; /// Whenever more than [receiveTimeout] passes between two events from response stream, -/// [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT]. +/// [Dio] will throw the [DioException] with [DioExceptionType.RECEIVE_TIMEOUT]. /// Note: This is not the receiving time limitation. Duration? receiveTimeout; @@ -421,16 +421,16 @@ dio.interceptors.add( // If you want to resolve the request with custom data, // you can resolve a `Response` using `handler.resolve(response)`. // If you want to reject the request with a error message, - // you can reject with a `DioError` using `handler.reject(dioError)`. + // you can reject with a `DioException` using `handler.reject(dioError)`. return handler.next(options); }, onResponse: (Response response, ResponseInterceptorHandler handler) { // Do something with response data. // If you want to reject the request with a error message, - // you can reject a `DioError` object using `handler.reject(dioError)`. + // you can reject a `DioException` object using `handler.reject(dioError)`. return handler.next(response); }, - onError: (DioError e, ErrorInterceptorHandler handler) { + onError: (DioException e, ErrorInterceptorHandler handler) { // Do something with response error. // If you want to resolve the request with some custom data, // you can resolve a `Response` object using `handler.resolve(response)`. @@ -458,7 +458,7 @@ class CustomInterceptors extends Interceptor { } @override - Future onError(DioError err, ErrorInterceptorHandler handler) async { + Future onError(DioException err, ErrorInterceptorHandler handler) async { print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}'); super.onError(err, handler); } @@ -525,13 +525,13 @@ There is an example that implementing a simple cache policy: ## Handling Errors -When an error occurs, Dio will wrap the `Error/Exception` to a `DioError`: +When an error occurs, Dio will wrap the `Error/Exception` to a `DioException`: ```dart try { // 404 await dio.get('https://api.pub.dev/not-exist'); -} on DioError catch (e) { +} on DioException catch (e) { // The request was made and the server responded with a status code // that falls out of the range of 2xx and is also not 304. if (e.response != null) { @@ -546,7 +546,7 @@ try { } ``` -### DioError +### DioException ```dart /// The request info for the request that throws exception. @@ -556,24 +556,24 @@ RequestOptions requestOptions; /// HTTP server, for example, occurring a DNS error, network is not available. Response? response; -/// The type of the current [DioError]. -DioErrorType type; +/// The type of the current [DioException]. +DioExceptionType type; /// The original error/exception object; -/// It's usually not null when `type` is [DioErrorType.unknown]. +/// It's usually not null when `type` is [DioExceptionType.unknown]. Object? error; /// The stacktrace of the original error/exception object; -/// It's usually not null when `type` is [DioErrorType.unknown]. +/// It's usually not null when `type` is [DioExceptionType.unknown]. StackTrace? stackTrace; -/// The error message that throws a [DioError]. +/// The error message that throws a [DioException]. String? message; ``` -### DioErrorType +### DioExceptionType -See [the source code](lib/src/dio_error.dart). +See [the source code](lib/src/dio_exception.dart). ## Using application/x-www-form-urlencoded format @@ -869,7 +869,7 @@ When a token's `cancel()` is invoked, all requests with this token will be cance ```dart final cancelToken = CancelToken(); -dio.get(url, cancelToken: cancelToken).catchError((DioError err) { +dio.get(url, cancelToken: cancelToken).catchError((DioException err) { if (CancelToken.isCancel(err)) { print('Request canceled: ${err.message}'); } else { diff --git a/dio/lib/dio.dart b/dio/lib/dio.dart index 873c41aa7..aead831ef 100644 --- a/dio/lib/dio.dart +++ b/dio/lib/dio.dart @@ -6,7 +6,7 @@ library dio; export 'src/adapter.dart'; export 'src/cancel_token.dart'; export 'src/dio.dart'; -export 'src/dio_error.dart'; +export 'src/dio_exception.dart'; export 'src/dio_mixin.dart' hide InterceptorState, InterceptorResultType; export 'src/form_data.dart'; export 'src/headers.dart'; diff --git a/dio/lib/src/adapters/browser_adapter.dart b/dio/lib/src/adapters/browser_adapter.dart index 5bea9501c..b252a10bf 100644 --- a/dio/lib/src/adapters/browser_adapter.dart +++ b/dio/lib/src/adapters/browser_adapter.dart @@ -5,7 +5,7 @@ import 'dart:typed_data'; import 'package:meta/meta.dart'; import '../adapter.dart'; -import '../dio_error.dart'; +import '../dio_exception.dart'; import '../headers.dart'; import '../options.dart'; @@ -86,7 +86,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter { xhr.abort(); completer.completeError( - DioError.connectionTimeout( + DioException.connectionTimeout( requestOptions: options, timeout: connectionTimeout, ), @@ -114,7 +114,10 @@ class BrowserHttpClientAdapter implements HttpClientAdapter { if (duration > sendTimeout) { uploadStopwatch.stop(); completer.completeError( - DioError.sendTimeout(timeout: sendTimeout, requestOptions: options), + DioException.sendTimeout( + timeout: sendTimeout, + requestOptions: options, + ), StackTrace.current, ); xhr.abort(); @@ -144,7 +147,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter { if (duration > receiveTimeout) { downloadStopwatch.stop(); completer.completeError( - DioError.receiveTimeout( + DioException.receiveTimeout( timeout: options.receiveTimeout!, requestOptions: options, ), @@ -166,7 +169,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter { // specific information about the error itself. // See also: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror completer.completeError( - DioError.connectionError( + DioException.connectionError( requestOptions: options, reason: 'The XMLHttpRequest onError callback was called. ' 'This typically indicates an error on the network layer.', @@ -186,7 +189,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter { // or added xhr.onAbort like axios did https://github.com/axios/axios/blob/master/lib/adapters/xhr.js#L102-L111 if (!completer.isCompleted) { completer.completeError( - DioError.requestCancelled( + DioException.requestCancelled( requestOptions: options, reason: 'The XMLHttpRequest was aborted.', ), diff --git a/dio/lib/src/adapters/io_adapter.dart b/dio/lib/src/adapters/io_adapter.dart index 9c0e0583b..0bc53c9fb 100644 --- a/dio/lib/src/adapters/io_adapter.dart +++ b/dio/lib/src/adapters/io_adapter.dart @@ -3,7 +3,7 @@ import 'dart:io'; import 'dart:typed_data'; import '../adapter.dart'; -import '../dio_error.dart'; +import '../dio_exception.dart'; import '../options.dart'; import '../redirect_record.dart'; @@ -75,7 +75,7 @@ class IOHttpClientAdapter implements HttpClientAdapter { request = await reqFuture.timeout( connectionTimeout, onTimeout: () { - throw DioError.connectionTimeout( + throw DioException.connectionTimeout( requestOptions: options, timeout: connectionTimeout, ); @@ -93,7 +93,7 @@ class IOHttpClientAdapter implements HttpClientAdapter { if (!e.message.contains('timed out')) { rethrow; } - throw DioError.connectionTimeout( + throw DioException.connectionTimeout( requestOptions: options, timeout: options.connectTimeout ?? httpClient.connectionTimeout ?? @@ -115,7 +115,7 @@ class IOHttpClientAdapter implements HttpClientAdapter { sendTimeout, onTimeout: () { request.abort(); - throw DioError.sendTimeout( + throw DioException.sendTimeout( timeout: sendTimeout, requestOptions: options, ); @@ -132,7 +132,7 @@ class IOHttpClientAdapter implements HttpClientAdapter { future = future.timeout( receiveTimeout, onTimeout: () { - throw DioError.receiveTimeout( + throw DioException.receiveTimeout( timeout: receiveTimeout, requestOptions: options, ); @@ -151,9 +151,9 @@ class IOHttpClientAdapter implements HttpClientAdapter { port, ); if (!isCertApproved) { - throw DioError( + throw DioException( requestOptions: options, - type: DioErrorType.badCertificate, + type: DioExceptionType.badCertificate, error: responseStream.certificate, message: 'The certificate of the response is not approved.', ); @@ -168,7 +168,7 @@ class IOHttpClientAdapter implements HttpClientAdapter { final receiveTimeout = options.receiveTimeout; if (receiveTimeout != null && duration > receiveTimeout) { sink.addError( - DioError.receiveTimeout( + DioException.receiveTimeout( timeout: receiveTimeout, requestOptions: options, ), diff --git a/dio/lib/src/cancel_token.dart b/dio/lib/src/cancel_token.dart index b049deb4c..292018ab8 100644 --- a/dio/lib/src/cancel_token.dart +++ b/dio/lib/src/cancel_token.dart @@ -1,6 +1,6 @@ import 'dart:async'; -import 'dio_error.dart'; +import 'dio_exception.dart'; import 'options.dart'; /// An instance which controls cancellation of [Dio]'s requests, @@ -12,14 +12,15 @@ import 'options.dart'; class CancelToken { CancelToken(); - final Completer _completer = Completer(); + final Completer _completer = Completer(); /// Whether the [error] is thrown by [cancel]. - static bool isCancel(DioError error) => error.type == DioErrorType.cancel; + static bool isCancel(DioException error) => + error.type == DioExceptionType.cancel; /// If request have been canceled, save the cancel error. - DioError? get cancelError => _cancelError; - DioError? _cancelError; + DioException? get cancelError => _cancelError; + DioException? _cancelError; RequestOptions? requestOptions; @@ -27,11 +28,11 @@ class CancelToken { bool get isCancelled => _cancelError != null; /// When cancelled, this future will be resolved. - Future get whenCancel => _completer.future; + Future get whenCancel => _completer.future; /// Cancel the request with the given [reason]. void cancel([Object? reason]) { - _cancelError = DioError.requestCancelled( + _cancelError = DioException.requestCancelled( requestOptions: requestOptions ?? RequestOptions(), reason: reason, stackTrace: StackTrace.current, diff --git a/dio/lib/src/dio/dio_for_native.dart b/dio/lib/src/dio/dio_for_native.dart index e4940a575..f256bc8f5 100644 --- a/dio/lib/src/dio/dio_for_native.dart +++ b/dio/lib/src/dio/dio_for_native.dart @@ -3,12 +3,12 @@ import 'dart:io'; import '../adapter.dart'; import '../cancel_token.dart'; +import '../dio_exception.dart'; import '../dio_mixin.dart'; import '../response.dart'; import '../dio.dart'; import '../headers.dart'; import '../options.dart'; -import '../dio_error.dart'; import '../adapters/io_adapter.dart'; Dio createDio([BaseOptions? baseOptions]) => DioForNative(baseOptions); @@ -49,8 +49,8 @@ class DioForNative with DioMixin implements Dio { queryParameters: queryParameters, cancelToken: cancelToken ?? CancelToken(), ); - } on DioError catch (e) { - if (e.type == DioErrorType.badResponse) { + } on DioException catch (e) { + if (e.type == DioExceptionType.badResponse) { if (e.response!.requestOptions.receiveDataWhenStatusError == true) { final res = await transformer.transformResponse( e.response!.requestOptions..responseType = ResponseType.json, @@ -140,7 +140,7 @@ class DioForNative with DioMixin implements Dio { await subscription.cancel(); } finally { completer.completeError( - DioMixin.assureDioError(e, response.requestOptions), + DioMixin.assureDioException(e, response.requestOptions), ); } }); @@ -153,7 +153,7 @@ class DioForNative with DioMixin implements Dio { completer.complete(response); } catch (e) { completer.completeError( - DioMixin.assureDioError(e, response.requestOptions), + DioMixin.assureDioException(e, response.requestOptions), ); } }, @@ -162,7 +162,7 @@ class DioForNative with DioMixin implements Dio { await closeAndDelete(); } finally { completer.completeError( - DioMixin.assureDioError(e, response.requestOptions), + DioMixin.assureDioException(e, response.requestOptions), ); } }, @@ -180,7 +180,7 @@ class DioForNative with DioMixin implements Dio { await subscription.cancel(); await closeAndDelete(); if (e is TimeoutException) { - throw DioError.receiveTimeout( + throw DioException.receiveTimeout( timeout: timeout, requestOptions: response.requestOptions, error: e, diff --git a/dio/lib/src/dio_error.dart b/dio/lib/src/dio_exception.dart similarity index 65% rename from dio/lib/src/dio_error.dart rename to dio/lib/src/dio_exception.dart index 8dd361d4c..9e0c33c07 100644 --- a/dio/lib/src/dio_error.dart +++ b/dio/lib/src/dio_exception.dart @@ -1,7 +1,16 @@ import 'options.dart'; import 'response.dart'; -enum DioErrorType { +/// Deprecated in favor of [DioExceptionType] and will be removed in future major versions. +@Deprecated('Use DioException instead. This will be removed in 6.0.0') +typedef DioErrorType = DioExceptionType; + +/// [DioError] describes the exception info when a request failed. +/// Deprecated in favor of [DioException] and will be removed in future major versions. +@Deprecated('Use DioException instead. This will be removed in 6.0.0') +typedef DioError = DioException; + +enum DioExceptionType { /// Caused by a connection timeout. connectionTimeout, @@ -14,7 +23,7 @@ enum DioErrorType { /// Caused by an incorrect certificate as configured by [ValidateCertificate]. badCertificate, - /// The [DioError] was caused by an incorrect status code as configured by + /// The [DioException] was caused by an incorrect status code as configured by /// [ValidateStatus]. badResponse, @@ -25,41 +34,41 @@ enum DioErrorType { connectionError, /// Default error type, Some other [Error]. In this case, you can use the - /// [DioError.error] if it is not null. + /// [DioException.error] if it is not null. unknown, } -extension _DioErrorTypeExtension on DioErrorType { +extension _DioExceptionTypeExtension on DioExceptionType { String toPrettyDescription() { switch (this) { - case DioErrorType.connectionTimeout: + case DioExceptionType.connectionTimeout: return 'connection timeout'; - case DioErrorType.sendTimeout: + case DioExceptionType.sendTimeout: return 'send timeout'; - case DioErrorType.receiveTimeout: + case DioExceptionType.receiveTimeout: return 'receive timeout'; - case DioErrorType.badCertificate: + case DioExceptionType.badCertificate: return 'bad certificate'; - case DioErrorType.badResponse: + case DioExceptionType.badResponse: return 'bad response'; - case DioErrorType.cancel: + case DioExceptionType.cancel: return 'request cancelled'; - case DioErrorType.connectionError: + case DioExceptionType.connectionError: return 'connection error'; - case DioErrorType.unknown: + case DioExceptionType.unknown: return 'unknown'; } } } -/// [DioError] describes the exception info when a request failed. -class DioError implements Exception { +/// [DioException] describes the exception info when a request failed. +class DioException implements Exception { /// Prefer using one of the other constructors. /// They're most likely better fitting. - DioError({ + DioException({ required this.requestOptions, this.response, - this.type = DioErrorType.unknown, + this.type = DioExceptionType.unknown, this.error, StackTrace? stackTrace, this.message, @@ -69,13 +78,13 @@ class DioError implements Exception { requestOptions.sourceStackTrace ?? StackTrace.current; - factory DioError.badResponse({ + factory DioException.badResponse({ required int statusCode, required RequestOptions requestOptions, required Response response, }) => - DioError( - type: DioErrorType.badResponse, + DioException( + type: DioExceptionType.badResponse, message: 'The request returned an ' 'invalid status code of $statusCode.', requestOptions: requestOptions, @@ -83,13 +92,13 @@ class DioError implements Exception { error: null, ); - factory DioError.connectionTimeout({ + factory DioException.connectionTimeout({ required Duration timeout, required RequestOptions requestOptions, Object? error, }) => - DioError( - type: DioErrorType.connectionTimeout, + DioException( + type: DioExceptionType.connectionTimeout, message: 'The request connection took ' 'longer than $timeout. It was aborted.', requestOptions: requestOptions, @@ -97,12 +106,12 @@ class DioError implements Exception { error: error, ); - factory DioError.sendTimeout({ + factory DioException.sendTimeout({ required Duration timeout, required RequestOptions requestOptions, }) => - DioError( - type: DioErrorType.sendTimeout, + DioException( + type: DioExceptionType.sendTimeout, message: 'The request took ' 'longer than $timeout to send data. It was aborted.', requestOptions: requestOptions, @@ -110,13 +119,13 @@ class DioError implements Exception { error: null, ); - factory DioError.receiveTimeout({ + factory DioException.receiveTimeout({ required Duration timeout, required RequestOptions requestOptions, Object? error, }) => - DioError( - type: DioErrorType.receiveTimeout, + DioException( + type: DioExceptionType.receiveTimeout, message: 'The request took ' 'longer than $timeout to receive data. It was aborted.', requestOptions: requestOptions, @@ -124,13 +133,13 @@ class DioError implements Exception { error: error, ); - factory DioError.requestCancelled({ + factory DioException.requestCancelled({ required RequestOptions requestOptions, required Object? reason, StackTrace? stackTrace, }) => - DioError( - type: DioErrorType.cancel, + DioException( + type: DioExceptionType.cancel, message: 'The request was cancelled.', requestOptions: requestOptions, response: null, @@ -138,12 +147,12 @@ class DioError implements Exception { stackTrace: stackTrace, ); - factory DioError.connectionError({ + factory DioException.connectionError({ required RequestOptions requestOptions, required String reason, }) => - DioError( - type: DioErrorType.connectionError, + DioException( + type: DioExceptionType.connectionError, message: 'The connection errored: $reason', requestOptions: requestOptions, response: null, @@ -157,29 +166,29 @@ class DioError implements Exception { /// HTTP server, for example, occurring a DNS error, network is not available. final Response? response; - final DioErrorType type; + final DioExceptionType type; /// The original error/exception object; - /// It's usually not null when `type` is [DioErrorType.unknown]. + /// It's usually not null when `type` is [DioExceptionType.unknown]. final Object? error; /// The stacktrace of the original error/exception object; - /// It's usually not null when `type` is [DioErrorType.unknown]. + /// It's usually not null when `type` is [DioExceptionType.unknown]. final StackTrace stackTrace; - /// The error message that throws a [DioError]. + /// The error message that throws a [DioException]. final String? message; - /// Generate a new [DioError] by combining given values and original values. - DioError copyWith({ + /// Generate a new [DioException] by combining given values and original values. + DioException copyWith({ RequestOptions? requestOptions, Response? response, - DioErrorType? type, + DioExceptionType? type, Object? error, StackTrace? stackTrace, String? message, }) { - return DioError( + return DioException( requestOptions: requestOptions ?? this.requestOptions, response: response ?? this.response, type: type ?? this.type, @@ -191,7 +200,7 @@ class DioError implements Exception { @override String toString() { - String msg = 'DioError [${type.toPrettyDescription()}]: $message'; + String msg = 'DioException [${type.toPrettyDescription()}]: $message'; if (error != null) { msg += '\nError: $error'; } diff --git a/dio/lib/src/dio_mixin.dart b/dio/lib/src/dio_mixin.dart index 960ffb3b1..0571796e8 100644 --- a/dio/lib/src/dio_mixin.dart +++ b/dio/lib/src/dio_mixin.dart @@ -9,7 +9,7 @@ import 'package:meta/meta.dart'; import 'adapter.dart'; import 'cancel_token.dart'; import 'dio.dart'; -import 'dio_error.dart'; +import 'dio_exception.dart'; import 'form_data.dart'; import 'headers.dart'; import 'interceptors/imply_content_type.dart'; @@ -373,7 +373,7 @@ abstract class DioMixin implements Dio { ); if (_closed) { - throw DioError.connectionError( + throw DioException.connectionError( reason: "Dio can't establish a new connection after it was closed.", requestOptions: requestOptions, ); @@ -447,7 +447,7 @@ abstract class DioMixin implements Dio { return (err) { final state = err is InterceptorState ? err - : InterceptorState(assureDioError(err, requestOptions)); + : InterceptorState(assureDioException(err, requestOptions)); Future handleError() async { final errorHandler = ErrorInterceptorHandler(); interceptor(state.data, errorHandler); @@ -456,7 +456,8 @@ abstract class DioMixin implements Dio { // The request has already been canceled, // there is no need to listen for another cancellation. - if (state.data is DioError && state.data.type == DioErrorType.cancel) { + if (state.data is DioException && + state.data.type == DioExceptionType.cancel) { return handleError(); } else if (state.type == InterceptorResultType.next || state.type == InterceptorResultType.rejectCallFollowing) { @@ -496,7 +497,7 @@ abstract class DioMixin implements Dio { _dispatchRequest(reqOpt) .then((value) => handler.resolve(value, true)) .catchError((e) { - handler.reject(e as DioError, true); + handler.reject(e as DioException, true); }); }), ); @@ -516,7 +517,7 @@ abstract class DioMixin implements Dio { : interceptor.onError; future = future.catchError(errorInterceptorWrapper(fun)); } - // Normalize errors, we convert error to the DioError. + // Normalize errors, we convert error to the DioException. return future.then>((data) { return assureResponse( data is InterceptorState ? data.data : data, @@ -529,7 +530,7 @@ abstract class DioMixin implements Dio { return assureResponse(e.data, requestOptions); } } - throw assureDioError(isState ? e.data : e, requestOptions); + throw assureDioException(isState ? e.data : e, requestOptions); }); } @@ -566,14 +567,14 @@ abstract class DioMixin implements Dio { if (statusOk) { return ret; } else { - throw DioError.badResponse( + throw DioException.badResponse( statusCode: responseBody.statusCode, requestOptions: reqOpt, response: ret, ); } } catch (e) { - throw assureDioError(e, reqOpt); + throw assureDioException(e, reqOpt); } } @@ -689,15 +690,15 @@ abstract class DioMixin implements Dio { } @internal - static DioError assureDioError( + static DioException assureDioException( Object err, RequestOptions requestOptions, ) { - if (err is DioError) { + if (err is DioException) { // nothing to be done return err; } - return DioError( + return DioException( requestOptions: requestOptions, error: err, ); diff --git a/dio/lib/src/interceptor.dart b/dio/lib/src/interceptor.dart index bc36faccd..2d1682fb7 100644 --- a/dio/lib/src/interceptor.dart +++ b/dio/lib/src/interceptor.dart @@ -63,9 +63,12 @@ class RequestInterceptorHandler extends _BaseHandler { /// /// [error]: Error info to reject. /// [callFollowingErrorInterceptor]: Whether to call the error interceptor(s). - void reject(DioError error, [bool callFollowingErrorInterceptor = false]) { + void reject( + DioException error, [ + bool callFollowingErrorInterceptor = false, + ]) { _completer.completeError( - InterceptorState( + InterceptorState( error, callFollowingErrorInterceptor ? InterceptorResultType.rejectCallFollowing @@ -104,9 +107,12 @@ class ResponseInterceptorHandler extends _BaseHandler { /// /// [error]: Error info to reject. /// [callFollowingErrorInterceptor]: Whether to call the error interceptor(s). - void reject(DioError error, [bool callFollowingErrorInterceptor = false]) { + void reject( + DioException error, [ + bool callFollowingErrorInterceptor = false, + ]) { _completer.completeError( - InterceptorState( + InterceptorState( error, callFollowingErrorInterceptor ? InterceptorResultType.rejectCallFollowing @@ -121,9 +127,9 @@ class ResponseInterceptorHandler extends _BaseHandler { /// Handler for error interceptor. class ErrorInterceptorHandler extends _BaseHandler { /// Continue to call the next error interceptor. - void next(DioError err) { + void next(DioException err) { _completer.completeError( - InterceptorState(err), + InterceptorState(err), err.stackTrace, ); _processNextInQueue?.call(); @@ -144,9 +150,9 @@ class ErrorInterceptorHandler extends _BaseHandler { } /// Complete the request with a error directly! Other error interceptor(s) will not be executed. - void reject(DioError error) { + void reject(DioException error) { _completer.completeError( - InterceptorState( + InterceptorState( error, InterceptorResultType.reject, ), @@ -177,7 +183,7 @@ class Interceptor { /// you can resolve a [Response] object with [handler.resolve]. /// /// If you want to complete the request with an error message, - /// you can reject a [DioError] object with [handler.reject]. + /// you can reject a [DioException] object with [handler.reject]. void onRequest( RequestOptions options, RequestInterceptorHandler handler, @@ -193,7 +199,7 @@ class Interceptor { /// response interceptor(s) will not be executed. /// /// If you want to complete the response with an error message, - /// you can reject a [DioError] object with [handler.reject]. + /// you can reject a [DioException] object with [handler.reject]. void onResponse( Response response, ResponseInterceptorHandler handler, @@ -210,10 +216,10 @@ class Interceptor { /// error interceptor(s) will be skipped. /// /// If you want to complete the response with an error message directly, - /// you can reject a [DioError] object with [handler.reject], and other + /// you can reject a [DioException] object with [handler.reject], and other /// error interceptor(s) will be skipped. void onError( - DioError err, + DioException err, ErrorInterceptorHandler handler, ) { handler.next(err); @@ -231,7 +237,7 @@ typedef InterceptorSuccessCallback = void Function( ); typedef InterceptorErrorCallback = void Function( - DioError e, + DioException e, ErrorInterceptorHandler handler, ); @@ -266,7 +272,7 @@ mixin _InterceptorWrapperMixin on Interceptor { @override void onError( - DioError err, + DioException err, ErrorInterceptorHandler handler, ) { if (_onError != null) { @@ -375,7 +381,7 @@ class QueuedInterceptor extends Interceptor { } void _handleError( - DioError err, + DioException err, ErrorInterceptorHandler handler, ) { _handleQueue(_errorQueue, err, handler, onError); diff --git a/dio/lib/src/interceptors/log.dart b/dio/lib/src/interceptors/log.dart index 9429a0e73..04f647077 100644 --- a/dio/lib/src/interceptors/log.dart +++ b/dio/lib/src/interceptors/log.dart @@ -1,4 +1,4 @@ -import '../dio_error.dart'; +import '../dio_exception.dart'; import '../dio_mixin.dart'; import '../options.dart'; import '../response.dart'; @@ -92,9 +92,9 @@ class LogInterceptor extends Interceptor { } @override - void onError(DioError err, ErrorInterceptorHandler handler) async { + void onError(DioException err, ErrorInterceptorHandler handler) async { if (error) { - logPrint('*** DioError ***:'); + logPrint('*** DioException ***:'); logPrint('uri: ${err.requestOptions.uri}'); logPrint('$err'); if (err.response != null) { diff --git a/dio/lib/src/options.dart b/dio/lib/src/options.dart index 22eedb98b..e43849216 100644 --- a/dio/lib/src/options.dart +++ b/dio/lib/src/options.dart @@ -189,7 +189,7 @@ mixin OptionsMixin { late Map queryParameters; /// Timeout in milliseconds for opening url. - /// [Dio] will throw the [DioError] with [DioErrorType.connectionTimeout] type + /// [Dio] will throw the [DioException] with [DioExceptionType.connectionTimeout] type /// when time out. Duration? get connectTimeout => _connectTimeout; @@ -354,7 +354,7 @@ class Options { Map? headers; /// Timeout in milliseconds for sending data. - /// [Dio] will throw the [DioError] with [DioErrorType.sendTimeout] type + /// [Dio] will throw the [DioException] with [DioExceptionType.sendTimeout] type /// when time out. Duration? get sendTimeout => _sendTimeout; @@ -691,7 +691,7 @@ class _RequestConfig { } /// Timeout in milliseconds for sending data. - /// [Dio] will throw the [DioError] with [DioErrorType.sendTimeout] type + /// [Dio] will throw the [DioException] with [DioExceptionType.sendTimeout] type /// when time out. /// /// `null` meanings no timeout limit. diff --git a/dio/test/basic_test.dart b/dio/test/basic_test.dart index 31619341b..1c54ad9b5 100644 --- a/dio/test/basic_test.dart +++ b/dio/test/basic_test.dart @@ -42,11 +42,13 @@ void main() { await expectLater( Dio().get('http://http.invalid'), throwsA(allOf([ - isA(), - (DioError e) => + isA(), + (DioException e) => e.type == - (isWeb ? DioErrorType.connectionError : DioErrorType.unknown), - if (!isWeb) (DioError e) => e.error is SocketException, + (isWeb + ? DioExceptionType.connectionError + : DioExceptionType.unknown), + if (!isWeb) (DioException e) => e.error is SocketException, ])), ); }); @@ -63,7 +65,7 @@ void main() { await expectLater( dio.get('/test-timeout', cancelToken: token), - throwsA((e) => e is DioError && CancelToken.isCancel(e)), + throwsA((e) => e is DioException && CancelToken.isCancel(e)), ); }); @@ -75,8 +77,8 @@ void main() { dio.get('/401'), throwsA( (e) => - e is DioError && - e.type == DioErrorType.badResponse && + e is DioException && + e.type == DioExceptionType.badResponse && e.response!.statusCode == 401, ), ); diff --git a/dio/test/cancel_token_test.dart b/dio/test/cancel_token_test.dart index bfbdcb5fc..a6d1e8a9d 100644 --- a/dio/test/cancel_token_test.dart +++ b/dio/test/cancel_token_test.dart @@ -3,13 +3,13 @@ import 'package:test/test.dart'; void main() { group(CancelToken, () { - test('cancel returns the correct DioError', () async { + test('cancel returns the correct DioException', () async { final token = CancelToken(); const reason = 'cancel'; expectLater(token.whenCancel, completion((error) { - return error is DioError && - error.type == DioErrorType.cancel && + return error is DioException && + error.type == DioExceptionType.cancel && error.error == reason; })); token.requestOptions = RequestOptions(); diff --git a/dio/test/download_test.dart b/dio/test/download_test.dart index 9cab3ba45..cdc0e4d50 100644 --- a/dio/test/download_test.dart +++ b/dio/test/download_test.dart @@ -47,7 +47,7 @@ void main() { dio.options.baseUrl = serverUrl.toString(); Response response = await dio .download('/error', savePath) - .catchError((e) => (e as DioError).response!); + .catchError((e) => (e as DioException).response!); expect(response.data, 'error'); response = await dio .download( @@ -55,7 +55,7 @@ void main() { savePath, options: Options(receiveDataWhenStatusError: false), ) - .catchError((e) => (e as DioError).response!); + .catchError((e) => (e as DioException).response!); expect(response.data, null); }); @@ -70,8 +70,8 @@ void main() { expect( dio .download('/download', savePath) - .catchError((e) => throw (e as DioError).type), - throwsA(DioErrorType.receiveTimeout), + .catchError((e) => throw (e as DioException).type), + throwsA(DioExceptionType.receiveTimeout), ); //print(r); }); @@ -89,8 +89,8 @@ void main() { savePath, cancelToken: cancelToken, ) - .catchError((e) => throw (e as DioError).type), - throwsA(DioErrorType.cancel), + .catchError((e) => throw (e as DioException).type), + throwsA(DioExceptionType.cancel), ); }); diff --git a/dio/test/exception_test.dart b/dio/test/exception_test.dart index 537f26682..869d37ee2 100644 --- a/dio/test/exception_test.dart +++ b/dio/test/exception_test.dart @@ -7,39 +7,39 @@ import 'package:test/test.dart'; void main() { /// https://github.com/cfug/diox/issues/66 - test('Ensure DioError is an Exception', () { - final error = DioError(requestOptions: RequestOptions()); + test('Ensure DioException is an Exception', () { + final error = DioException(requestOptions: RequestOptions()); expect(error, isA()); }); - test('catch DioError', () async { - DioError? error; + test('catch DioException', () async { + DioException? error; try { await Dio().get('https://does.not.exist'); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); }); - test('catch DioError as Exception', () async { - DioError? error; + test('catch DioException as Exception', () async { + DioException? error; try { await Dio().get('https://does.not.exist'); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); }); - test('catch DioError: hostname mismatch', () async { - DioError? error; + test('catch DioException: hostname mismatch', () async { + DioException? error; try { await Dio().get('https://wrong.host.badssl.com/'); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); diff --git a/dio/test/interceptor_test.dart b/dio/test/interceptor_test.dart index 4d752e1e5..80a5abb11 100644 --- a/dio/test/interceptor_test.dart +++ b/dio/test/interceptor_test.dart @@ -55,23 +55,24 @@ void main() { ); break; case '/reject': - handler.reject(DioError(requestOptions: reqOpt, error: 3)); + handler + .reject(DioException(requestOptions: reqOpt, error: 3)); break; case '/reject-next': handler.reject( - DioError(requestOptions: reqOpt, error: 4), + DioException(requestOptions: reqOpt, error: 4), true, ); break; case '/reject-next/reject': handler.reject( - DioError(requestOptions: reqOpt, error: 5), + DioException(requestOptions: reqOpt, error: 5), true, ); break; case '/reject-next-response': handler.reject( - DioError(requestOptions: reqOpt, error: 5), + DioException(requestOptions: reqOpt, error: 5), true, ); break; @@ -94,7 +95,7 @@ void main() { break; case '/resolve-next/reject': handler.reject( - DioError( + DioException( requestOptions: options, error: '/resolve-next/reject', ), @@ -102,7 +103,7 @@ void main() { break; case '/resolve-next/reject-next': handler.reject( - DioError(requestOptions: options, error: ''), + DioException(requestOptions: options, error: ''), true, ); break; @@ -257,11 +258,11 @@ void main() { dio .get('/test') .then(handler.resolve) - .catchError((e) => handler.reject(e as DioError)); + .catchError((e) => handler.reject(e as DioException)); break; case '/fakepath3': handler.reject( - DioError( + DioException( requestOptions: options, error: 'test error', ), @@ -269,7 +270,7 @@ void main() { break; case '/fakepath4': handler.reject( - DioError( + DioException( requestOptions: options, error: 'test error', ), @@ -297,17 +298,17 @@ void main() { expect( dio.get('/fakepath3'), throwsA( - isA() + isA() .having((e) => e.message, 'message', null) - .having((e) => e.type, 'error type', DioErrorType.unknown), + .having((e) => e.type, 'error type', DioExceptionType.unknown), ), ); expect( dio.get('/fakepath4'), throwsA( - isA() + isA() .having((e) => e.message, 'message', null) - .having((e) => e.type, 'error type', DioErrorType.unknown), + .having((e) => e.type, 'error type', DioExceptionType.unknown), ), ); @@ -420,7 +421,7 @@ void main() { response.data = response.data['data']; handler.next(response); }, - onError: (DioError e, ErrorInterceptorHandler handler) { + onError: (DioException e, ErrorInterceptorHandler handler) { if (e.response?.requestOptions != null) { switch (e.response!.requestOptions.path) { case urlNotFound: @@ -456,7 +457,7 @@ void main() { expect( dio .get(urlNotFound) - .catchError((e) => throw (e as DioError).response!.statusCode!), + .catchError((e) => throw (e as DioException).response!.statusCode!), throwsA(404), ); response = await dio.get('${urlNotFound}1'); @@ -464,8 +465,8 @@ void main() { response = await dio.get('${urlNotFound}2'); expect(response.data, 'fake data'); expect( - dio.get('${urlNotFound}3').catchError((e) => throw e as DioError), - throwsA(isA()), + dio.get('${urlNotFound}3').catchError((e) => throw e as DioException), + throwsA(isA()), ); }); test('multi response interceptor', () async { @@ -507,13 +508,13 @@ void main() { group('Error Interceptor', () { test('handled when request cancelled', () async { final cancelToken = CancelToken(); - DioError? iError, qError; + DioException? iError, qError; final dio = Dio() ..httpClientAdapter = MockAdapter() ..options.baseUrl = MockAdapter.mockBase ..interceptors.add( InterceptorsWrapper( - onError: (DioError e, ErrorInterceptorHandler handler) { + onError: (DioException e, ErrorInterceptorHandler handler) { iError = e; handler.next(e); }, @@ -521,7 +522,7 @@ void main() { ) ..interceptors.add( QueuedInterceptorsWrapper( - onError: (DioError e, ErrorInterceptorHandler handler) { + onError: (DioException e, ErrorInterceptorHandler handler) { qError = e; handler.next(e); }, @@ -533,8 +534,8 @@ void main() { await dio .get('/test-timeout', cancelToken: cancelToken) .then((_) {}, onError: (_) {}); - expect(iError, isA()); - expect(qError, isA()); + expect(iError, isA()); + expect(qError, isA()); }); }); @@ -559,7 +560,7 @@ void main() { csrfToken = d.data['data']['token'] as String; handler.next(options); }).catchError((e) { - handler.reject(e as DioError, true); + handler.reject(e as DioException, true); }); } else { options.headers['csrfToken'] = csrfToken; @@ -612,7 +613,7 @@ void main() { dio .fetch(options) .then(handler.resolve) - .catchError((e) => handler.reject(e as DioError)); + .catchError((e) => handler.reject(e as DioException)); return; } // update token and repeat @@ -626,7 +627,7 @@ void main() { dio .fetch(options) .then(handler.resolve) - .catchError((e) => handler.reject(e as DioError)); + .catchError((e) => handler.reject(e as DioException)); }); } else { handler.next(error); diff --git a/dio/test/options_test.dart b/dio/test/options_test.dart index 0d0a6fc33..7f18566e6 100644 --- a/dio/test/options_test.dart +++ b/dio/test/options_test.dart @@ -406,7 +406,7 @@ void main() { // Throws a type error during cast. expectLater( dio.get>('/test-plain-text-content-type'), - throwsA((e) => e is DioError && e.error is TypeError), + throwsA((e) => e is DioException && e.error is TypeError), ); }); @@ -430,7 +430,7 @@ void main() { void testInvalidArgumentException(String method) async { await expectLater( dio.fetch(RequestOptions(path: 'http://127.0.0.1', method: method)), - throwsA((e) => e is DioError && e.error is ArgumentError), + throwsA((e) => e is DioException && e.error is ArgumentError), ); } diff --git a/dio/test/pinning_test.dart b/dio/test/pinning_test.dart index 9bed3bfaa..2b6fc4db0 100644 --- a/dio/test/pinning_test.dart +++ b/dio/test/pinning_test.dart @@ -23,19 +23,19 @@ void main() { }); test('pinning: untrusted host rejected with no approver', () async { - DioError? error; + DioException? error; try { final dio = Dio(); await dio.get(untrustedCertUrl); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); }); test('pinning: every certificate tested and rejected', () async { - DioError? error; + DioException? error; try { final dio = Dio(); dio.httpClientAdapter = IOHttpClientAdapter( @@ -43,7 +43,7 @@ void main() { ); await dio.get(trustedCertUrl); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); @@ -85,7 +85,7 @@ void main() { test( 'pinning: untrusted certificate rejected before validateCertificate', () async { - DioError? error; + DioException? error; try { final dio = Dio(); dio.httpClientAdapter = IOHttpClientAdapter( @@ -102,7 +102,7 @@ void main() { options: Options(validateStatus: (status) => true), ); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); @@ -110,7 +110,7 @@ void main() { ); test('bad pinning: badCertCallback does not use leaf certificate', () async { - DioError? error; + DioException? error; try { final dio = Dio(); dio.httpClientAdapter = IOHttpClientAdapter( @@ -130,7 +130,7 @@ void main() { options: Options(validateStatus: (status) => true), ); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); diff --git a/dio/test/readtimeout_test.dart b/dio/test/readtimeout_test.dart index bc4f88243..8b3747181 100644 --- a/dio/test/readtimeout_test.dart +++ b/dio/test/readtimeout_test.dart @@ -55,7 +55,7 @@ void main() { tearDown(stopServer); test( - 'catch DioError when receiveTimeout < $_sleepDurationAfterConnectionEstablished', + 'catch DioException when receiveTimeout < $_sleepDurationAfterConnectionEstablished', () async { final dio = Dio(); @@ -64,22 +64,22 @@ void main() { ..receiveTimeout = _sleepDurationAfterConnectionEstablished - Duration(seconds: 1); - DioError error; + DioException error; try { await dio.get('/'); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); //print(error); - expect(error.type == DioErrorType.receiveTimeout, isTrue); + expect(error.type == DioExceptionType.receiveTimeout, isTrue); }); test( - 'no DioError when receiveTimeout > $_sleepDurationAfterConnectionEstablished', + 'no DioException when receiveTimeout > $_sleepDurationAfterConnectionEstablished', () async { final dio = Dio(); @@ -88,11 +88,11 @@ void main() { ..connectTimeout = _sleepDurationAfterConnectionEstablished + Duration(seconds: 1); - DioError? error; + DioException? error; try { await dio.get('/'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; print(e.requestOptions.uri); } @@ -113,13 +113,13 @@ void main() { try { await dio.get('/'); - } on DioError catch (_) {} + } on DioException catch (_) {} expect(http.connectionTimeout?.inMilliseconds == 200, isTrue); try { dio.options.connectTimeout = Duration(seconds: 1); await dio.get('/'); - } on DioError catch (_) {} + } on DioException catch (_) {} expect(http.connectionTimeout?.inSeconds == 1, isTrue); }); } diff --git a/dio/test/request_test.dart b/dio/test/request_test.dart index 097d95fd5..cd49e293b 100644 --- a/dio/test/request_test.dart +++ b/dio/test/request_test.dart @@ -79,7 +79,7 @@ void main() { expect( dio .get('/error') - .catchError((e) => throw (e as DioError).response!.statusCode!), + .catchError((e) => throw (e as DioException).response!.statusCode!), throwsA(equals(400)), ); diff --git a/dio/test/stacktrace_test.dart b/dio/test/stacktrace_test.dart index 1ca4fa249..2f405f207 100644 --- a/dio/test/stacktrace_test.dart +++ b/dio/test/stacktrace_test.dart @@ -11,8 +11,8 @@ import 'mock/http_mock.dart'; import 'mock/http_mock.mocks.dart'; void main() async { - group('$DioError.stackTrace', () { - test(DioErrorType.badResponse, () async { + group('$DioException.stackTrace', () { + test(DioExceptionType.badResponse, () async { final dio = Dio(BaseOptions()) ..httpClientAdapter = MockAdapter() ..options.baseUrl = MockAdapter.mockBase; @@ -20,15 +20,15 @@ void main() async { await expectLater( dio.get('/foo'), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.badResponse, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.badResponse, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); }); - test(DioErrorType.cancel, () async { + test(DioExceptionType.cancel, () async { final dio = Dio(BaseOptions()) ..httpClientAdapter = MockAdapter() ..options.baseUrl = MockAdapter.mockBase; @@ -42,16 +42,16 @@ void main() async { await expectLater( dio.get('/test-timeout', cancelToken: token), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.cancel, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.cancel, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); }); test( - DioErrorType.connectionTimeout, + DioExceptionType.connectionTimeout, () async { await HttpOverrides.runWithHttpOverrides(() async { final timeout = Duration(milliseconds: 10); @@ -69,9 +69,9 @@ void main() async { await expectLater( dio.get('/test'), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.connectionTimeout, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.connectionTimeout, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); @@ -81,7 +81,7 @@ void main() async { ); test( - DioErrorType.receiveTimeout, + DioExceptionType.receiveTimeout, () async { await HttpOverrides.runWithHttpOverrides(() async { final timeout = Duration(milliseconds: 10); @@ -102,9 +102,9 @@ void main() async { await expectLater( dio.get('/test'), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.receiveTimeout, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.receiveTimeout, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); @@ -114,7 +114,7 @@ void main() async { ); test( - DioErrorType.sendTimeout, + DioExceptionType.sendTimeout, () async { await HttpOverrides.runWithHttpOverrides(() async { final timeout = Duration(milliseconds: 10); @@ -136,9 +136,9 @@ void main() async { await expectLater( dio.get('/test', data: 'some data'), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.sendTimeout, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.sendTimeout, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); @@ -148,7 +148,7 @@ void main() async { ); test( - DioErrorType.badCertificate, + DioExceptionType.badCertificate, () async { await HttpOverrides.runWithHttpOverrides(() async { final dio = Dio(BaseOptions()..baseUrl = 'https://does.not.exist') @@ -166,9 +166,9 @@ void main() async { await expectLater( dio.get('/test'), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.badCertificate, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.badCertificate, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); @@ -178,7 +178,7 @@ void main() async { ); test( - DioErrorType.unknown, + DioExceptionType.unknown, () async { final dio = Dio(BaseOptions()..baseUrl = 'https://does.not.exist'); @@ -189,10 +189,10 @@ void main() async { data: Object(), ), throwsA(allOf([ - isA(), - (DioError e) => e.type == DioErrorType.unknown, - (DioError e) => e.error is JsonUnsupportedObjectError, - (DioError e) => + isA(), + (DioException e) => e.type == DioExceptionType.unknown, + (DioException e) => e.error is JsonUnsupportedObjectError, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), ); @@ -214,7 +214,7 @@ void main() async { }, ), InterceptorsWrapper(onRequest: (options, handler) { - final error = DioError( + final error = DioException( error: Error(), requestOptions: options, ); @@ -225,9 +225,9 @@ void main() async { await expectLater( dio.get('/error'), throwsA(allOf([ - isA(), - (DioError e) => e.stackTrace == caughtStackTrace, - (DioError e) => + isA(), + (DioException e) => e.stackTrace == caughtStackTrace, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), reason: 'Stacktrace should be available in onError', @@ -248,7 +248,7 @@ void main() async { }, ), QueuedInterceptorsWrapper(onRequest: (options, handler) { - final error = DioError( + final error = DioException( error: Error(), requestOptions: options, ); @@ -259,9 +259,9 @@ void main() async { await expectLater( dio.get('/error'), throwsA(allOf([ - isA(), - (DioError e) => e.stackTrace == caughtStackTrace, - (DioError e) => + isA(), + (DioException e) => e.stackTrace == caughtStackTrace, + (DioException e) => e.stackTrace.toString().contains('test/stacktrace_test.dart'), ])), reason: 'Stacktrace should be available in onError', diff --git a/example/lib/certificate_pinning.dart b/example/lib/certificate_pinning.dart index 93dc67206..037eedac6 100644 --- a/example/lib/certificate_pinning.dart +++ b/example/lib/certificate_pinning.dart @@ -55,7 +55,7 @@ void main() async { // This certificate doesn't have the same fingerprint. response = await dio.get('https://bad.host.badssl.com/'); print(response.data); - } on DioError catch (e) { + } on DioException catch (e) { print(e.message); print(response?.data); dio.close(force: true); diff --git a/example/lib/custom_cache_interceptor.dart b/example/lib/custom_cache_interceptor.dart index 2c890cf03..025f90bd8 100644 --- a/example/lib/custom_cache_interceptor.dart +++ b/example/lib/custom_cache_interceptor.dart @@ -25,7 +25,7 @@ class CacheInterceptor extends Interceptor { } @override - void onError(DioError err, ErrorInterceptorHandler handler) { + void onError(DioException err, ErrorInterceptorHandler handler) { print('onError: $err'); super.onError(err, handler); } diff --git a/example/lib/dio.dart b/example/lib/dio.dart index 30a3ad27d..999a6e823 100644 --- a/example/lib/dio.dart +++ b/example/lib/dio.dart @@ -31,7 +31,7 @@ void main() async { InterceptorsWrapper( onRequest: (options, handler) { // return handler.resolve( Response(data:"xxx")); - // return handler.reject( DioError(message: "eh")); + // return handler.reject( DioException(message: "eh")); return handler.next(options); }, ), diff --git a/example/lib/generic.dart b/example/lib/generic.dart index 4106a9107..75c269d27 100644 --- a/example/lib/generic.dart +++ b/example/lib/generic.dart @@ -30,7 +30,7 @@ void main() async { // it will cause a Error (type 'String' is not a subtype of type 'Map') try { response = await dio.get('https://baidu.com'); - } on DioError catch (e) { + } on DioException catch (e) { print(e.message); } diff --git a/example/lib/queued_interceptor_crsftoken.dart b/example/lib/queued_interceptor_crsftoken.dart index 4dfed44cc..4b38207e5 100644 --- a/example/lib/queued_interceptor_crsftoken.dart +++ b/example/lib/queued_interceptor_crsftoken.dart @@ -35,7 +35,7 @@ void main() async { } return handler.reject( - DioError(requestOptions: result.requestOptions), + DioException(requestOptions: result.requestOptions), true, ); } @@ -72,7 +72,7 @@ void main() async { } print('the token has not been updated'); return handler.reject( - DioError(requestOptions: options), + DioException(requestOptions: options), ); } return handler.next(error); diff --git a/example/lib/request_interceptors.dart b/example/lib/request_interceptors.dart index 104be8165..d29e967cf 100644 --- a/example/lib/request_interceptors.dart +++ b/example/lib/request_interceptors.dart @@ -23,7 +23,7 @@ void main() async { break; case '/fakepath3': return handler.reject( - DioError( + DioException( requestOptions: options, error: 'test error', ), @@ -41,7 +41,7 @@ void main() async { assert(response.data['headers'] is Map); try { response = await dio.get('/fakepath3'); - } on DioError catch (e) { + } on DioException catch (e) { assert(e.message == 'test error'); assert(e.response == null); } @@ -49,7 +49,7 @@ void main() async { assert(response.data['headers'] is Map); try { await dio.get('/status/404'); - } on DioError catch (e) { + } on DioException catch (e) { assert(e.response!.statusCode == 404); } } diff --git a/example/lib/response_interceptor.dart b/example/lib/response_interceptor.dart index 318d57129..76e5de827 100644 --- a/example/lib/response_interceptor.dart +++ b/example/lib/response_interceptor.dart @@ -15,7 +15,7 @@ void main() async { response.data = json.decode(response.data['data']); handler.next(response); }, - onError: (DioError e, handler) { + onError: (DioException e, handler) { if (e.response != null) { switch (e.response!.requestOptions.path) { case urlNotFound: @@ -57,7 +57,7 @@ void main() async { assert(response.data['a'] == 5); try { await dio.get(urlNotFound); - } on DioError catch (e) { + } on DioException catch (e) { assert(e.response!.statusCode == 404); } response = await dio.get('${urlNotFound}1'); @@ -66,7 +66,7 @@ void main() async { assert(response.data == 'fake data'); try { await dio.get('${urlNotFound}3'); - } on DioError catch (e) { + } on DioException catch (e) { assert(e.message == 'custom error info [404]'); } } diff --git a/example/lib/transformer.dart b/example/lib/transformer.dart index d40e0b2d7..6ca955937 100644 --- a/example/lib/transformer.dart +++ b/example/lib/transformer.dart @@ -11,7 +11,7 @@ class MyTransformer extends BackgroundTransformer { @override Future transformRequest(RequestOptions options) async { if (options.data is List) { - throw DioError( + throw DioException( error: "Can't send List to sever directly", requestOptions: options, ); diff --git a/plugins/cookie_manager/CHANGELOG.md b/plugins/cookie_manager/CHANGELOG.md index 2f452e5ba..edae20380 100644 --- a/plugins/cookie_manager/CHANGELOG.md +++ b/plugins/cookie_manager/CHANGELOG.md @@ -2,11 +2,12 @@ ## Unreleased -*None.* +- Replace `DioError` with `DioException`. ## 3.0.0 ### Breaking changes + - Bump cookie_jar from 3.0.0 to 4.0.0. Upgrading to this version will lose all previous cookies. @@ -28,25 +29,25 @@ ## 2.1.1 -* Fix #1651 -* Fix #1674 +- Fix #1651 +- Fix #1674 ## 2.1.0 -* For the `dio`'s 5.0 release. +- For the `dio`'s 5.0 release. ## 2.0.0 -* support dio 4.0.0 +- support dio 4.0.0 ## 2.0.0-beta1 -* support nullsafety +- support nullsafety ## 1.0.0 - 2019.9.18 -* First stable version +- First stable version ## 0.0.1 - 2019.9.17 -* A cookie manager for Dio. +- A cookie manager for Dio. diff --git a/plugins/cookie_manager/lib/src/cookie_mgr.dart b/plugins/cookie_manager/lib/src/cookie_mgr.dart index 19e7c6c22..271926a27 100644 --- a/plugins/cookie_manager/lib/src/cookie_mgr.dart +++ b/plugins/cookie_manager/lib/src/cookie_mgr.dart @@ -61,7 +61,11 @@ class CookieManager extends Interceptor { newCookies.isNotEmpty ? newCookies : null; handler.next(options); }).catchError((dynamic e, StackTrace s) { - final err = DioError(requestOptions: options, error: e, stackTrace: s); + final err = DioException( + requestOptions: options, + error: e, + stackTrace: s, + ); handler.reject(err, true); }); } @@ -70,7 +74,7 @@ class CookieManager extends Interceptor { void onResponse(Response response, ResponseInterceptorHandler handler) { _saveCookies(response).then((_) => handler.next(response)).catchError( (dynamic e, StackTrace s) { - final err = DioError( + final err = DioException( requestOptions: response.requestOptions, error: e, stackTrace: s, @@ -81,11 +85,11 @@ class CookieManager extends Interceptor { } @override - void onError(DioError err, ErrorInterceptorHandler handler) { + void onError(DioException err, ErrorInterceptorHandler handler) { if (err.response != null) { _saveCookies(err.response!).then((_) => handler.next(err)).catchError( (dynamic e, StackTrace s) { - final error = DioError( + final error = DioException( requestOptions: err.response!.requestOptions, error: e, stackTrace: s, diff --git a/plugins/cookie_manager/pubspec.yaml b/plugins/cookie_manager/pubspec.yaml index c81aad0ed..111f018fb 100644 --- a/plugins/cookie_manager/pubspec.yaml +++ b/plugins/cookie_manager/pubspec.yaml @@ -6,11 +6,11 @@ repository: https://github.com/cfug/dio/blob/main/plugins/cookie_manager issue_tracker: https://github.com/cfug/dio/issues environment: - sdk: '>=2.15.0 <3.0.0' + sdk: ">=2.15.0 <3.0.0" dependencies: cookie_jar: ^4.0.0 - dio: ^5.0.0 + dio: ^5.2.0 dev_dependencies: lints: any diff --git a/plugins/http2_adapter/CHANGELOG.md b/plugins/http2_adapter/CHANGELOG.md index 85d4feb25..73cac109c 100644 --- a/plugins/http2_adapter/CHANGELOG.md +++ b/plugins/http2_adapter/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -*None.* +- Replace `DioError` with `DioException`. ## 2.2.0 diff --git a/plugins/http2_adapter/lib/src/connection_manager_imp.dart b/plugins/http2_adapter/lib/src/connection_manager_imp.dart index 2b9d1af22..c016534f5 100644 --- a/plugins/http2_adapter/lib/src/connection_manager_imp.dart +++ b/plugins/http2_adapter/lib/src/connection_manager_imp.dart @@ -79,7 +79,7 @@ class _ConnectionManager implements ConnectionManager { } on SocketException catch (e) { if (e.osError == null) { if (e.message.contains('timed out')) { - throw DioError.connectionTimeout( + throw DioException.connectionTimeout( timeout: options.connectTimeout!, requestOptions: options, ); @@ -95,9 +95,9 @@ class _ConnectionManager implements ConnectionManager { uri.port, ); if (!isCertApproved) { - throw DioError( + throw DioException( requestOptions: options, - type: DioErrorType.badCertificate, + type: DioExceptionType.badCertificate, error: socket.peerCertificate, message: 'The certificate of the response is not approved.', ); @@ -170,10 +170,10 @@ class _ConnectionManager implements ConnectionManager { final completerProxyInitialization = Completer(); Never onProxyError(Object? error, StackTrace stackTrace) { - throw DioError( + throw DioException( requestOptions: options, error: error, - type: DioErrorType.connectionError, + type: DioExceptionType.connectionError, stackTrace: stackTrace, ); } diff --git a/plugins/http2_adapter/pubspec.yaml b/plugins/http2_adapter/pubspec.yaml index b72669e7e..7afa14e63 100644 --- a/plugins/http2_adapter/pubspec.yaml +++ b/plugins/http2_adapter/pubspec.yaml @@ -6,11 +6,11 @@ repository: https://github.com/cfug/dio/blob/main/plugins/http2_adapter issue_tracker: https://github.com/cfug/dio/issues environment: - sdk: '>=2.15.0 <3.0.0' + sdk: ">=2.15.0 <3.0.0" dependencies: http2: ^2.0.0 - dio: ^5.0.0 + dio: ^5.2.0 dev_dependencies: crypto: ^3.0.2 diff --git a/plugins/http2_adapter/test/pinning_test.dart b/plugins/http2_adapter/test/pinning_test.dart index 3fcf51fd3..a7a1dc462 100644 --- a/plugins/http2_adapter/test/pinning_test.dart +++ b/plugins/http2_adapter/test/pinning_test.dart @@ -45,7 +45,7 @@ void main() { }); test('untrusted host rejected with no approver', () async { - DioError? error; + DioException? error; try { dio.httpClientAdapter = Http2Adapter( ConnectionManager( @@ -58,7 +58,7 @@ void main() { ); await dio.get('get'); fail('did not throw'); - } on DioError catch (e) { + } on DioException catch (e) { error = e; } expect(error, isNotNull); diff --git a/plugins/native_dio_adapter/CHANGELOG.md b/plugins/native_dio_adapter/CHANGELOG.md index 7a9fb75e2..1a678d84e 100644 --- a/plugins/native_dio_adapter/CHANGELOG.md +++ b/plugins/native_dio_adapter/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -*None.* +- Replace `DioError` with `DioException`. ## 0.1.0 diff --git a/plugins/native_dio_adapter/pubspec.yaml b/plugins/native_dio_adapter/pubspec.yaml index c1e52a33d..8017d6edb 100644 --- a/plugins/native_dio_adapter/pubspec.yaml +++ b/plugins/native_dio_adapter/pubspec.yaml @@ -6,11 +6,11 @@ repository: https://github.com/cfug/dio/blob/main/plugins/native_dio_adapter issue_tracker: https://github.com/cfug/dio/issues environment: - sdk: '>=2.19.0 <3.0.0' + sdk: ">=2.19.0 <3.0.0" flutter: ">=3.7.0" dependencies: - dio: ^5.0.0 + dio: ^5.2.0 cupertino_http: ^0.1.2 cronet_http: ^0.2.0 http: ^0.13.4 @@ -25,4 +25,4 @@ platforms: ios: linux: macos: - windows: \ No newline at end of file + windows: