How to catch DatabaseError in Flutter Firebase App

為{幸葍}努か 提交于 2020-06-01 05:09:30

问题


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.

Below is the code

   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());
    }

But the Exception is never thrown or catch by the Android Studio, In logCat I can see the exception,

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)

but could not find a away to catch it in code and then act on the exception.


回答1:


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



来源:https://stackoverflow.com/questions/59978750/how-to-catch-databaseerror-in-flutter-firebase-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!