首页 > 解决方案 > 如何在 kotlin 中使用协程处理 firebase auth 错误?

问题描述

我有一个挂起功能,可以使用 firebase auth 注册用户。

我知道有 auth 错误代码,我怎样才能在 try cath 中获取它们?

我正在考虑使用e.message然后将它们翻译成我的语言,但我不知道这是否是一个好方法。

override suspend fun registerUserFirebase(email: String, password: String):Boolean {
    return try {
        auth.createUserWithEmailAndPassword(email, password).await()
        true
    } catch (e: Exception) {            
        if (e.message == "The email address is already in use by another account."){
            // Do stuff
        }
        false
    }
}

标签: androidfirebasekotlinfirebase-authentication

解决方案


关于协程,这里没有什么特别的。根据 API docs for createUserWithEmailAndPassword()可以产生不同类型的异常:

例外

  • 如果密码不够强,则抛出 FirebaseAuthWeakPasswordException
  • 如果电子邮件地址格式错误,则会引发 FirebaseAuthInvalidCredentialsException
  • 如果已经存在具有给定电子邮件地址的帐户,则会引发 FirebaseAuthUserCollisionException

您的代码将需要使用或可能使用检查异常的类型iswhen,并根据自己的条件确定如何处理每个异常。


推荐阅读