baseRequestList method
Implementation
Future<dynamic> baseRequestList({
final String? function,
final Map<String, dynamic>? params,
final dynamic postData,
final Map<String, String?>? headers,
final String? url,
//TODO: сделать настраиваемым параметром
//final int timeout = timeout,
final String method = 'GET',
final NsgCancelToken? cancelToken,
FutureOr<void> Function(Exception)? onRetry,
}) async {
final _dio = Dio(
BaseOptions(
headers: headers,
method: method,
responseType: ResponseType.json,
contentType: 'application/json',
connectTimeout: Duration(milliseconds: connectDuration),
receiveTimeout: Duration(milliseconds: requestDuration),
),
);
//Response<List<dynamic>> response;
late Response<dynamic> response;
try {
if (!kIsWeb) {
(_dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
final client = HttpClient();
client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
return client;
};
}
//Для отладки рассчитаем время выполнения функции
var counter = NsgDurationCounter();
if (isDebug) {
debugPrint('baseRequestList, function=$function');
}
//TODO: сделать генерацию метода запроса GET/POST
var method2 = 'POST';
var dioCancelToken = cancelToken?.dioCancelToken;
if (method2 == 'GET') {
response = await _dio.get(url!, queryParameters: params, cancelToken: dioCancelToken);
} else if (method2 == 'POST') {
response = await _dio.post(url!, queryParameters: params, data: postData, cancelToken: dioCancelToken);
}
if (isDebug) {
counter.difStart(paramName: 'baseRequestList, function=$function. ', criticalDuration: 1500);
}
return response.data;
} on DioException catch (e) {
debugPrint('dio error. function: $function, error: ${e.error ?? ''}');
if (e.response != null) {
debugPrint('statusCode: ${e.response?.statusCode}');
}
if (e.response?.statusCode == 400) {
//400 - Сервер отказался предоставлять данные. Повторять запрос бессмыслено
throw NsgApiException(NsgApiError(code: 400, message: e.response?.data, errorType: e.type));
}
if (e.response?.statusCode == 401) {
throw NsgApiException(NsgApiError(code: 401, message: 'Authorization error', errorType: e.type));
}
if (e.response?.statusCode == 500) {
var msg = 'ERROR 500';
if (e.response!.data is Map && (e.response!.data as Map).containsKey('message')) {
var msgParts = e.response!.data['message'].split('---> ');
//TODO: в нулевом параметре функция, вызвавшая ишибку - надо где-то показывать
msg = msgParts.last;
}
throw NsgApiException(NsgApiError(code: 500, message: msg, errorType: e.type));
} else if (e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout) {
throw NsgApiException(NsgApiError(code: 2, message: 'Timeout while receiving or sending data', errorType: e.type));
} else {
debugPrint('###');
debugPrint('### Error: ${e.error}, type: ${e.type}');
debugPrint('###');
throw NsgApiException(NsgApiError(code: 1, message: e.error?.toString() ?? 'Internet connection error', errorType: e.type));
}
} catch (e) {
debugPrint(
'network error. function: $function, error: $function + '
' + $e',
);
return NsgApiException(NsgApiError(code: 0, message: '$e'));
}
}