【发布时间】:2021-09-07 11:10:00
【问题描述】:
在https://pub.dev/packages/dio#handling-errors 的 Dart Dio 包文档中描述了如何处理错误:
try {
//404
await dio.get('https://wendux.github.io/xsddddd');
} on DioError catch (e) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
if (e.response) {
print(e.response.data)
print(e.response.headers)
print(e.response.request)
} else {
// Something happened in setting up or sending the request that triggered an Error
print(e.request)
print(e.message)
}
}
代码很有意义,并为我提供了了解我的请求发生了什么所需的选项,但 Android Studio 中的 Dart 分析工具(我正在开发一个 Flutter 应用程序)对此反应剧烈。
按照 Android Studio 的建议,我可以通过在代码中添加空检查来解决许多分析器的投诉:
try {
var response = await dio.get(url, options: options);
print('Response: $response');
return response.data;
} on DioError catch (e) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
if (e.response != null) {
print(e.response!.data);
print(e.response!.headers);
print(e.response!.request); <-- line 64
} else {
// Something happened in setting up or sending the request that triggered an Error
print(e.request); <-- line 67
print(e.message);
}
}
但分析器仍然抱怨request 对象:
error: The getter 'request' isn't defined for the type 'Response<dynamic>'. (undefined_getter at [particle_cloud] lib\src\particle.dart:64)
error: The getter 'request' isn't defined for the type 'DioError'. (undefined_getter at [particle_cloud] lib\src\particle.dart:67)
我假设 DioError 应该定义了适当的请求对象,我该如何修复此代码以使其运行?
【问题讨论】: