首页 > 解决方案 > 如何在 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)

但找不到在代码中捕获它然后对异常采取行动的方法。

标签: firebaseflutterexceptiondartfirebase-realtime-database

解决方案


您可以使用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


推荐阅读