Skip to content

Commit

Permalink
Deprecate DioError in favor of DioException (cfug#1803)
Browse files Browse the repository at this point in the history
### 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 cfug#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 <[email protected]>
Co-authored-by: Alex Li <[email protected]>
  • Loading branch information
clragon and AlexV525 authored May 15, 2023
1 parent 690896a commit 2603cc8
Show file tree
Hide file tree
Showing 40 changed files with 321 additions and 291 deletions.
12 changes: 7 additions & 5 deletions dio/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -246,7 +245,6 @@ Add `deleteOnError` parameter to `downloadUri`

- support flutter version>=1.8 (fix #357)


## 2.1.8

- fix #354 #312
Expand Down Expand Up @@ -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`

Expand Down
24 changes: 12 additions & 12 deletions dio/README-ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
* [多文件上传](#多文件上传)
Expand Down Expand Up @@ -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);
},
Expand All @@ -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);
}
Expand All @@ -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(
Expand Down Expand Up @@ -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) {
Expand All @@ -517,7 +517,7 @@ try {
}
```

### DioError
### DioException

```dart
/// 错误的请求对应的配置。
Expand All @@ -527,7 +527,7 @@ RequestOptions requestOptions;
Response? response;
/// 错误的类型。
DioErrorType type;
DioExceptionType type;
/// 实际错误的内容。
Object? error;
Expand All @@ -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 编码

Expand Down Expand Up @@ -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 {
Expand Down
36 changes: 18 additions & 18 deletions dio/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -304,7 +304,7 @@ Map<String, dynamic>? 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;
Expand Down Expand Up @@ -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)`.
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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) {
Expand All @@ -546,7 +546,7 @@ try {
}
```

### DioError
### DioException

```dart
/// The request info for the request that throws exception.
Expand All @@ -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

Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion dio/lib/dio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
15 changes: 9 additions & 6 deletions dio/lib/src/adapters/browser_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -86,7 +86,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {

xhr.abort();
completer.completeError(
DioError.connectionTimeout(
DioException.connectionTimeout(
requestOptions: options,
timeout: connectionTimeout,
),
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -144,7 +147,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
if (duration > receiveTimeout) {
downloadStopwatch.stop();
completer.completeError(
DioError.receiveTimeout(
DioException.receiveTimeout(
timeout: options.receiveTimeout!,
requestOptions: options,
),
Expand All @@ -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.',
Expand All @@ -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.',
),
Expand Down
Loading

0 comments on commit 2603cc8

Please sign in to comment.