You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Firebase Jetpack Compose中区分用户不存在与密码错误登录场景

区分Firebase登录的用户不存在与密码错误场景

Firebase在用户不存在和密码错误时确实会抛出同一个FirebaseAuthInvalidCredentialsException异常,但可以通过异常的错误码区分具体失败原因,进而给用户返回精准提示。

具体实现方案

  1. 获取异常错误码:通过FirebaseAuthInvalidCredentialsException的errorCode属性可拿到具体错误标识
  2. 匹配错误码区分场景:
    • user-not-found:对应用户不存在
    • wrong-password:对应密码错误

修改后的代码示例

override suspend fun signIn(email: String, password: String): Flow<Response<Boolean>> =
    callbackFlow {
        try {
            trySend(Response.Loading) // 建议将Loading状态放在任务发起前发送,保证状态流顺序正确
            auth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        trySend(Response.Success(true))
                        val user = auth.currentUser
                    } else {
                        task.exception?.let { e ->
                            if (e is FirebaseAuthInvalidCredentialsException) {
                                when(e.errorCode) {
                                    "user-not-found" -> {
                                        trySend(Response.Failure(IllegalArgumentException("用户不存在")))
                                    }
                                    "wrong-password" -> {
                                        trySend(Response.Failure(IllegalArgumentException("密码错误")))
                                    }
                                    else -> {
                                        trySend(Response.Failure(e))
                                    }
                                }
                            } else {
                                trySend(Response.Failure(e))
                            }
                        }
                    }
                }
        } catch (e: Exception) {
            trySend(Response.Failure(e))
        }

        awaitClose { }
    }

补充说明

  • 修正了原代码中task -的语法错误,改为task ->
  • 可根据需求扩展处理其他错误码(如invalid-email对应邮箱格式错误)
  • 你提供的异常信息翻译为:

RecaptchaAction(action=signInWithPassword)操作初始任务失败,异常信息:提供的身份验证凭据不正确、格式错误或已过期

内容的提问来源于stack exchange,提问作者Tushar Bhatia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:50:00