【问题标题】:How to return a exception message to the user in dart?如何在飞镖中向用户返回异常消息?
【发布时间】:2022-01-21 13:20:33
【问题描述】:

是否可以向用户返回异常消息?如果是,我该如何实现?我想让用户知道发生时返回的异常消息。另外,我不希望我的应用在异常发生时崩溃。

更具体地说,我想在用户尝试登录时将错误消息返回给用户。我使用 Firebase 作为我的身份验证提供程序。

为了更好地理解,我在下面包含了我的代码。

提前谢谢你。

 Future<User?> signInWithEmailAndPassword(
    String email,
    String password,
  ) async {
    try {
      final credential = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      return _userFromFirebase(credential.user);

      throw Exception('Some Error occured. ');
    } on auth.FirebaseAuthException catch (e, _) {
      print(e);

    } catch (e) {
      print(e);
    }
  }

【问题讨论】:

    标签: flutter dart exception error-handling firebase-authentication


    【解决方案1】:

    您可以使用 ScaffoldMessenger 向用户显示错误消息

       Future<User?> signInWithEmailAndPassword(
        BuildContext context,
        String email,
        String password,
      ) async {
        try {
          final credential = await _firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          return _userFromFirebase(credential.user);
          
          throw Exception('Some Error occured. ');
          
        } on auth.FirebaseAuthException catch (e, _) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(e.toString()),
        ));
        } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(e.toString()),
        ));
        }
      }
    

    【讨论】:

    • 错误被抛出给用户,但仍然在异常发生时应用程序崩溃。请问如何避免应用程序在异常发生时崩溃?
    • 应用程序 'throw Exception('Some Error occurred.');'是不是因为这条线而崩溃?
    • Exception has occurred. PlatformException (PlatformException(wrong-password, The password is invalid or the user does not have a password., {code: wrong-password, message: The password is invalid or the user does not have a password., nativeErrorMessage: The password is invalid or the user does not have a password., nativeErrorCode: 17009, additionalData: {}}, null)) 在我调试我的应用程序时,程序此时暂停并崩溃。
    • 当我在没有调试的情况下运行我的应用程序时程序不会崩溃。有没有办法以更有吸引力的方式返回错误消息?可能像敬酒消息一样?只要你知道。提前谢谢你:)
    • 我会试试这个,再次非常感谢你!干杯!
    猜你喜欢
    • 2020-11-28
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2022-07-09
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多