我正在学习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)] Unhandled Exception: 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
关于firebase - 如何在Flutter Firebase App中捕获DatabaseError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978750/