【发布时间】:2020-06-24 04:50:26
【问题描述】:
我想处理带有一些错误消息的 http 请求抖动,但我在这里遇到了很多错误。我只是根据建议做的,但它对我不起作用。请任何人帮助我 这是我调用 API 的函数
getData(data, apiUrl) async {
var tempUrl = _url + apiUrl + await _getToken();
Uri uri = Uri.parse(tempUrl);
var fullUrl = uri.replace(queryParameters: data);
var res;
try {
var response = await http.get(fullUrl, headers: _setHeaders()).timeout(
const Duration(seconds: 60));
print(response.statusCode);
if (response.statusCode != 200) {
res = {
"success": false,
"status": response.statusCode,
"message": _returnResponse(response)
};
}
else {
res = response;
}
}
on SocketException {
throw FetchDataException('No Internet connection');
}
on TimeoutException catch (e) {
res = {
"success": false,
"status": response.statusCode,
"message": "Connection timeout"
};
} on Error catch (e) {
print('Error: $e');
}
return res;
}
这是我对除 200 以外的其他人的回复
dynamic _returnResponse(http.Response response) {
switch (response.statusCode) {
case 400:
throw BadRequestException(response.body.toString());
case 401:
case 403:
throw UnauthorisedException(response.body.toString());
case 500:
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response
.statusCode}');
}
}
这是我从 StackOverflow 和其他论坛获得的 app_exception.dart
class AppException implements Exception {
final _message;
final _prefix;
AppException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class FetchDataException extends AppException {
FetchDataException([String message])
: super(message, "Error During Communication: ");
}
class BadRequestException extends AppException {
BadRequestException([message]) : super(message, "Invalid Request: ");
}
class UnauthorisedException extends AppException {
UnauthorisedException([message]) : super(message, "Unauthorised: ");
}
class InvalidInputException extends AppException {
InvalidInputException([String message]) : super(message, "Invalid Input: ");
}
我尝试了很多建议,但根本没有用
我收到了这个错误
错误:“SocketException”不是一种类型。 在 SocketException { ^^^^^^^^^^^^^^^
错误:“TimeoutException”不是一种类型。 在 TimeoutException 上捕获 (e) { ^^^^^^^^^^^^^^^^
【问题讨论】:
标签: flutter http dart exception httprequest