在Firebase Jetpack Compose中区分用户不存在与密码错误登录场景
区分Firebase登录的用户不存在与密码错误场景
Firebase在用户不存在和密码错误时确实会抛出同一个FirebaseAuthInvalidCredentialsException异常,但可以通过异常的错误码区分具体失败原因,进而给用户返回精准提示。
具体实现方案
- 获取异常错误码:通过
FirebaseAuthInvalidCredentialsException的errorCode属性可拿到具体错误标识 - 匹配错误码区分场景:
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
相关产品推荐
相关产品推荐

