Firebase阻塞云函数在Unity用户注册时未返回自定义错误信息求助
问题分析与解决方案
核心问题
你通过beforeSignIn触发器拦截未验证邮箱的登录请求,但Unity端无法收到自定义错误信息,本质是Firebase Auth在自动登录流程中会对Cloud Functions抛出的错误做封装,部分错误类型(比如invalid-argument)不会完整透传到客户端。另外,依赖登录错误触发验证邮件的逻辑存在风险,不如直接在用户创建成功后发送邮件更可靠。
修正步骤
1. 调整Cloud Functions的错误类型
将invalid-argument替换为permission-denied,该错误类型属于权限类,Firebase会完整传递错误信息到客户端:
exports.beforeSignIn = functions.auth.user().beforeSignIn((user, context) => { if (user.email && !user.emailVerified) { throw new functions.auth.HttpsError( 'permission-denied', `${user.email} 需要先验证邮箱才能登录。`); } });
重新部署函数:
firebase deploy --only functions:beforeSignIn
2. 优化Unity端错误捕获与邮件发送逻辑
不要依赖登录错误触发邮件发送,因为CreateUserWithEmailAndPasswordAsync成功创建用户后,auth.CurrentUser已经存在,此时直接发送验证邮件即可(确保只发一次,因为用户创建流程仅执行一次)。同时优化异常捕获,强转成FirebaseException获取精准错误信息:
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWithOnMainThread(task => { if (task.IsCanceled || task.IsFaulted) { foreach (var exception in task.Exception.InnerExceptions) { if (exception is FirebaseException fbEx) { Debug.LogError($"登录拦截提示: {fbEx.Message}"); // 此处可根据错误信息引导用户去验证邮箱 } else { Debug.LogError("注册失败: " + exception.Message); } } onFailure?.Invoke(); return; } // 用户创建成功,直接发送验证邮件 auth.CurrentUser.SendEmailVerificationAsync().ContinueWithOnMainThread(sendTask => { if (sendTask.IsCompletedSuccessfully) { Debug.Log("验证邮件已发送至你的邮箱"); } else if (sendTask.IsFaulted) { Debug.LogError("发送验证邮件失败: " + sendTask.Exception?.InnerException?.Message); } }); });
3. 额外检查项
- 确认Firebase控制台中,你的项目已启用邮箱/密码登录方式。
- 检查Unity的Firebase SDK是否为最新版本,旧版本可能存在错误透传的bug。
- 确保Cloud Functions部署成功,可在Firebase控制台的「函数」页面查看触发器状态。
内容的提问来源于stack exchange,提问作者Waxx
相关产品推荐
相关产品推荐

