英文:
flutter: how can I got the exact error response from API without DioError formating?
问题
我想根据API错误向用户显示不同的消息。
问题是Dio将所有409
错误拦截为冲突,并每次显示相同的消息。
API错误响应是:
有没有办法在没有dioErrors的情况下使用或处理错误?
我的DioService:
...
注意:这只是我处理的POST请求。
调用API的服务
...
英文:
I want to display different messages to users based on the API error.
the problem is that Dio intercepts all 409
errors as a conflict and displays the same message every time.
I/flutter ( 4507): 🐛 12:06:44.286125 DEBUG Global Loggy - DioError [bad response]: The request returned an invalid status code of 409.
but API error response is:
{
"title": "PALLET_NOT_CREATED",
"status": 409,
"detail": "Cannot create a new pallet, the preparer has already a pallet in status IN_PROGRESS",
"timestamp": 1686218442060,
"developerMessage": "SOME MESSAGE ERE",
"code": "WMS_CLT_ERR_4",
"errors": {}
}
is there's anyway i can use or handle errors without dioErrors ?
my DioService:
...
Future<Response<JSON>> post({
required String endpoint,
JSON? data,
Options? options,
CancelToken? cancelToken,
}) async {
final response = await _dio.post<JSON>(
baseUrl + endpoint,
data: data,
options: options,
cancelToken: cancelToken ?? _cancelToken,
);
return response;
}
...
> NOTE: THIS IS ONLY THE POST REQUEST I HANDLED ALL OTHER METHODS`
service calling API
Future<PalletModel> createPallet(int batchId) async {
try {
final res = await _dioService.post(
endpoint: CommonProperties.palletsByBatchId.replaceAll(
":batchId",
batchId.toString(),
),
data: {},
options: Options(
extra: {
'requiresAuthToken': true,
},
),
);
return PalletModel.fromJson(res.data!);
} catch (e) {
logDebug('error is:');
logDebug(e);
rethrow;
}
}
答案1
得分: 1
你可以在你的 API post
调用中应用 try/catch
,在捕获 DioError 后,你可以操控数据,检查响应体等。
英文:
you can apply try/cath
to your api post
call
Future<Response<JSON>> post({
required String endpoint,
JSON? data,
Options? options,
CancelToken? cancelToken,
}) async {
try {
final response = await _dio.post<JSON>(
baseUrl + endpoint,
data: data,
options: options,
cancelToken: cancelToken ?? _cancelToken,
return response;
);
}
on DioError catch(e) {
print(e.response!.data.toString)
}
}
After catching a DioError, you can manipulate data, checking response body, etc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论