firebase - 如何在 Flutter Firebase 应用程序中捕获 DatabaseError
问题描述
我正在学习 Flutter,我想在 Flutter 应用程序/设备上捕获应该抛出的异常(因为安全规则正确拒绝它)。
下面是代码
try {
FirebaseDatabase.instance.reference().once().then((DataSnapshot snapshot) {
try {
debugPrint(snapshot.toString());
}
on DatabaseError catch (eIn1) {
debugPrint(' onRoot ' + eIn1.toString());
}
});
}on DatabaseError catch (eOut1) {
debugPrint(' on1 ' + eOut1.toString());
}
try {
FirebaseDatabase.instance.reference().child("todo").once().then((DataSnapshot snapshot) {
try {
debugPrint(snapshot.toString());
}
on DatabaseError catch (eIn2) {
debugPrint(' onNode ' + eIn2.toString());
}
});
}on Exception catch (eOut2) {
debugPrint(' on2 ' + eOut2.toString());
}
但是Android Studio永远不会抛出或捕获异常,在logCat中我可以看到异常,
com.example.flutterlogindemo E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未处理异常: DatabaseError(-3, Permission denied, ) #0 Query.once (package:firebase_database/src/query .dart:84:41) #1 _HomePageState.initState (package:flutter_login_demo/pages/home_page.dart:48:65)
但找不到在代码中捕获它然后对异常采取行动的方法。
解决方案
您可以使用catchError
来捕获错误:
FirebaseDatabase.instance.reference().child("todo").once().then((DataSnapshot snapshot) {
print(snapshot);
})
.catchError((error) {
print("Something went wrong: ${error.message}");
});
https://api.flutter.dev/flutter/package-async_async/DelegatingFuture/catchError.html
推荐阅读
- node.js - Stripe API无法自动扣款如何处理(Stripe API key)
- haskell - 如何打印出二维数组haskell
- flutter - 颤振获取pdf文件字符串数据到变量
- python - 在Tensorflow中,我不知道为什么我训练了一个模型,训练损失减少了,但似乎没有训练
- python - Pymysql Sql 立场有变量
- javascript - 前端Node JS的基本理解
- python - 将包安装到 PyCharm 时遇到问题
- html - 为什么前五个切片顺时针不悬停,而其余切片则悬停,有没有办法在每个“切片”的左侧和右侧放置边框?
- formula - 从 Google Sheet 到 WPS 电子表格的过滤功能
- nginx - CORS 已配置但无响应