如何在Flutter Firebase App中捕获DatabaseError [英] How to catch DatabaseError in Flutter Firebase App
问题描述
我正在学习Flutter,我想捕捉应该在Flutter应用程序/设备上抛出的异常(因为安全规则正确地拒绝了它)。
I am learning Flutter and I want to catch the exception that should be thrown ( as security rule is correctly rejecting it) at the Flutter Application/device.
下面是代码
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 I中可以看到异常,
But the Exception is never thrown or catch by the Android Studio, In logCat I can see the exception,
com.example.flutterlogindemo E / flutter:
[错误:flutter / lib / ui / ui_dart_state .cc(157)]未处理的异常:
DatabaseError(-3,权限被拒绝,)
#0 Query.once(package:firebase_database / src / query.dart:84:41)
#1 _HomePageState.initState(package:flutter_login_demo / pages / home_page.dart:48:65)
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
以捕获错误:
You can use the catchError
to be able to catch the error:
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
这篇关于如何在Flutter Firebase App中捕获DatabaseError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!