onError method

  1. @override
void onError(
  1. DioException err,
  2. ErrorInterceptorHandler handler
)
override

Called when an exception was occurred during the request.

Implementation

@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
  String? errorMessage;
  OnErrorHandler? onErrorHandler = HttpService.to.onErrorHandler;
  if (onErrorHandler != null) {
    errorMessage = await onErrorHandler(err);
  }
  if (errorMessage.isEmptyOrNull) {
    switch (err.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        errorMessage = '服务器连接超时';
        break;
      case DioExceptionType.connectionError:
        errorMessage = '服务器连接失败';
        break;
      case DioExceptionType.badCertificate:
        errorMessage = '无效的证书';
        break;
      case DioExceptionType.cancel:
        errorMessage = '请求取消';
        break;
      case DioExceptionType.unknown:
        if (await isNetworkAvailable()) {
          errorMessage = '服务器连接失败';
        } else {
          errorMessage = '设备未连接网络';
        }
        break;
      case DioExceptionType.badResponse:
        int? statusCode = err.response?.statusCode;
        if (statusCode != null) {
          errorMessage = '服务器异常:$statusCode';
        }
        break;
    }
  }
  handler.reject(
    DioException(
      type: err.type,
      message: errorMessage,
      requestOptions: err.requestOptions,
      response: err.response,
      error: null,
    ),
  );
}