我正在使用 dio 包實作 post 方法,當我嘗試在 dioError 中捕獲例外時,它不會捕獲任何錯誤,我使用攔截器,我發現應用程式永遠不會呼叫 one rror 方法。
我在不同的文章和帖子中進行了搜索,但沒有具體提到這個問題,我使用了 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 one rror(DioError err, ErrorInterceptorHandler handler) async{
debugPrint('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
super.onError(err, handler);
}
uj5u.com熱心網友回復:
嘗試在發布請求后檢查回應狀態。有時 API 不會生成例外,因此您需要對回應添加檢查statusCode。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/515396.html
標籤:扑api镖拦截器迪奥
