处理异常HTTP请求颤动



我想处理带有一些错误消息的http请求flutter,但这里有很多错误。我只是根据建议做的,但对我不起作用。请大家帮帮我这是我调用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({^^^^^^^^^^^^^^^^

我使用了dio包。这比我做的更容易,bug更少

https://pub.dev/packages/dio

如果发生的错误在SocketException和Timeout异常上,请确保在该文件中分别导入了dart.iodart.async。关于你的代码,我能够成功地运行它,但你可以一步一步地参考Paresh Mangukiya的答案,或者参考这里了解如何在flutter中使用自定义错误响应处理网络调用和异常的更多说明。

最新更新