flutter - 如何在颤动中捕获异常?
问题描述
这是我的例外课程。异常类已经由flutter的抽象异常类实现。我错过了什么吗?
class FetchDataException implements Exception {
final _message;
FetchDataException([this._message]);
String toString() {
if (_message == null) return "Exception";
return "Exception: $_message";
}
}
void loginUser(String email, String password) {
_data
.userLogin(email, password)
.then((user) => _view.onLoginComplete(user))
.catchError((onError) => {
print('error caught');
_view.onLoginError();
});
}
Future < User > userLogin(email, password) async {
Map body = {
'username': email,
'password': password
};
http.Response response = await http.post(apiUrl, body: body);
final responseBody = json.decode(response.body);
final statusCode = response.statusCode;
if (statusCode != HTTP_200_OK || responseBody == null) {
throw new FetchDataException(
"An error occured : [Status Code : $statusCode]");
}
return new User.fromMap(responseBody);
}
当状态不是 200 时,CatchError 不会捕获错误。简而言之,捕获的错误不会打印。
解决方案
尝试
void loginUser(String email, String password) async {
try {
var user = await _data
.userLogin(email, password);
_view.onLoginComplete(user);
});
} on FetchDataException catch(e) {
print('error caught: $e');
_view.onLoginError();
}
}
catchError
有时很难做到正确。使用async
/await
你可以使用try
/ catch
like 同步代码,而且通常更容易正确。
推荐阅读
- flutter - GoogleMap,如何在单击 Market en Flutter 时删除图标
- owasp - 当我使用小黄瓜脚本自动执行登录步骤时,Zap 扫描不起作用
- javascript - 为什么我的 if 语句在柏树中不起作用?
- reactjs - 未处理的拒绝 (TypeError):fs.createReadStream 不是函数。图片上传到 ipfs(pinata) 时出错
- powerbi - Power BI 使用报表上的字段将数据输入表中
- reactjs - Ag-Grid 在与下拉列表交互期间保持自定义过滤器打开
- jenkins - jenkins - 如何记录所有工作开始事件?
- logging - Elixir Logger 自定义元数据格式
- c++ - 在 OpenMP 中,如何指定不同类调用的函数之间的任务依赖关系?全局变量是唯一的解决方案吗?
- web-scraping - 无法让 Puppeteer 使用 click() 进行导航