我正在使用 dio 包实现 post 方法,当我尝试捕获 dioError 中的异常时,它不会捕获任何错误,我使用拦截器,我发现应用程序永远不会调用 OnError 方法。
我搜索了不同的文章和帖子,但没有具体提到这个问题,我使用 dio 版本 4.0.2 仍然有同样的问题,我尝试扩展异常文件中的 DioError 但什么也没发生
发帖方式:
@override
Future post(
String path, {
Map<String, dynamic>? body,
bool formDataIsEnabled = false,
Map<String, dynamic>? queryParams,
}) async {
try {
debugPrint("ENTERING THE POST METHOD:");
final response = await client.post(path,
queryParameters: queryParams,
data: formDataIsEnabled ? FormData.fromMap(body!) : body);
return _handleJsonResponse(response);
} on DioError catch (error) {
return _handleDioError(error);
}
}
处理方法:
dynamic _handleJsonResponse(Response<dynamic> response) {
final jsonResponse = jsonDecode(response.data);
return jsonResponse;
}
dynamic _handleDioError(DioError error) {
switch (error.type) {
case DioErrorType.connectTimeout:
break;
case DioErrorType.sendTimeout:
break;
case DioErrorType.receiveTimeout:
throw FetchDataException();
case DioErrorType.response:
switch (error.response?.statusCode) {
case StatusCode.badRequest:
throw BadRequestException();
case StatusCode.unauthorized:
case StatusCode.forbidden:
throw UnauthorisedException();
case StatusCode.notFound:
throw NotFoundException();
case StatusCode.conflict:
throw ConflictException();
case StatusCode.internalServerError:
throw InternalServerErrorException();
}
break;
case DioErrorType.cancel:
break;
case DioErrorType.other:
throw ServerExceptions(message: "Error");
}
}
拦截器:
class AppInterceptors extends Interceptor {
@override
Future onRequest(RequestOptions options, RequestInterceptorHandler handler) async{
debugPrint('REQUEST [${options.method}]=>PATH: ${options.path}');
options.headers[AppStrings.contentType] = AppStrings.applicationContentType;
super.onRequest(options, handler);
}
@override
Future onResponse(Response response, ResponseInterceptorHandler handler)async {
debugPrint('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
super.onResponse(response, handler);
}
@override
Future onError(DioError err, ErrorInterceptorHandler handler) async{
debugPrint('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
super.onError(err, handler);
}
尝试在发布请求后检查响应状态。有时 API 不会生成异常,因此您需要添加对响应的检查
statusCode
。