如何处理颤振中的异常? 为什么我不能有 response.data? ………………………………………………………………………………………………………………………………………………………………………………………… rhtrhehrh regjnoeriwjgnowiermnfgorewmfelrg
Future addFine(String apiToken, String uin, int type) async {
try {
Response response = await _dio.post(apiEndpoint + "fines",
options: Options(headers: {"Authorization": apiToken}),
data: {"uin": uin, "type": type});
print(response.data);
print(response.statusMessage);
print(response.statusCode);
} catch (error, stacktrace) {
print(error);
print(stacktrace);
return null;
}
}
my stack trace
I/flutter ( 5580): DioError [DioErrorType.RESPONSE]: Http status error [422]
I/flutter ( 5580): #0 DioMixin._dispatchRequest (package:dio/src/dio.dart:966:7)
I/flutter ( 5580): <asynchronous suspension>
I/flutter ( 5580): #1 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:849:37)
I/flutter ( 5580): #2 DioMixin.checkIfNeedEnqueue (package:dio/src/dio.dart:1121:22)
I/flutter ( 5580): #3 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:846:22)
I/flutter ( 5580): #4 new Future.<anonymous closure> (dart:async/future.dart:175:37)
I/flutter ( 5580): #5 _rootRun (dart:async/zone.dart:1182:47)
I/flutter ( 5580): #6 _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 5580): #7 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
I/flutter ( 5580): #8 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
I/flutter ( 5580): #9 _rootRun (dart:async/zone.dart:1190:13)
I/flutter ( 5580): #10 _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 5580): #11 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
I/flutter ( 5580): #12
Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15
答案 0 :(得分:0)
如果您认为代码表明错误是有效信息并且无论如何都想访问该信息,您可以自己决定,您认为什么是错误:
Response response = await _dio.post(apiEndpoint + "fines",
options: Options(
headers: {"Authorization": apiToken},
validateStatus: (status) => true),
data: {"uin": uin, "type": type});
在选项中,您可以传递一个确定哪些状态代码有效的验证器。在这种情况下,我只是让它使用任何代码。任何代码。您可能希望将其进一步限制在您的用例中,甚至可能是每次调用。例如,您可以将其限制为“OK”和“Unprocessable Entity”,例如 401 仍会引发异常:
validateStatus: (status) => { return status == 200 || status == 422; }