【问题标题】:How to get Firebase Exception into a switch statement如何将 Firebase 异常放入 switch 语句
【发布时间】:2017-01-15 09:06:10
【问题描述】:

我目前有这个代码:

if (!task.isSuccessful() && task.getException() != null) {
   FirebaseCrash.report(task.getException());
   Log.w(TAG, "signInWithCredential", task.getException());
   Toast.makeText(SignUp.this, "Authentication failed: " + task.getException().getMessage(),Toast.LENGTH_LONG).show();
}

有时用户得到一个FirebaseAuthUserCollisionException,我想在switch 语句中检测它,如下所示:

switch(task.getException()){
    case /*I don't know what goes here*/:
       //Whatever
}

但是当您阅读时,我不知道在case 语句中添加什么。我在里面放什么?换句话说,FirebaseAuthUserCollisionException 位于何处以便我可以访问它? FirebaseAuthUserCollisionException 只是一个类,所以我目前不能用它做任何事情。

【问题讨论】:

  • 同样的问题是discussed here。正如我所看到的,没有简单而干净的方法可以做你想做的事。除了这里的答案中介绍的方法,您还可以考虑this solution。

标签: android firebase firebase-authentication


【解决方案1】:

Firebase 身份验证异常都源自FirebaseAuthException,它有一个getErrorCode() 方法。

所以:

if(task.getException() instanceof FirebaseAuthException){
    FirebaseAuthException e = (FirebaseAuthException)task.getException();
    switch (e.getErrorCode()) {
        ...
    }
}

【讨论】:

  • 非常感谢,但如何获得“FirebaseAuthUserCollisionException”? case "FirebaseAuthUserCollisionException":?
  • switch case 不能在 Java 中测试类。如果您想要一个开关盒,您需要与getErrorCode() 进行比较。如果你想与班级进行比较,你需要像@rafal 所说的那样嵌套ifs。
  • 很好,但是我如何比较班级?如果这是真的,你为什么在你的答案中包含switch(e.getErrorCode())?顺便说一句,喜欢你的答案,非常有用:)
  • rafal 的回答显示了如何比较异常类。如果这对您不起作用,请显示您的操作代码(通过编辑您的问题)。
  • Frank:documentation for FirebaseAuthUserCollisionException 包含错误代码字符串常量的标识符(例如ERROR_EMAIL_ALREADY_IN_USE),但这些似乎不能作为某些类的公共成员访问。我是不是看的不够仔细?一位勤奋的开发人员在 Firebase 库中发现了这个 table of constants。
【解决方案2】:

试试:

if(task.getException() instanceof FirebaseAuthUserCollisionException){
    //whatever
}

【讨论】:

  • 如果其他异常是这个异常类的子类,它也属于这个类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 2013-07-31
  • 1970-01-01
  • 2021-07-30
相关资源
最近更新 更多