首页 > 解决方案 > 如何防止 Firebase Cloud Function 崩溃以及如何发送错误消息作为响应?

问题描述

我创建了一个createUser在调用时执行的简单函数。我有一个问题。当用户尝试使用已经存在的电子邮件注册时,该功能会崩溃。我的意思是,没关系,因为没有人希望有 2 个用户使用相同的电子邮件地址,但我想防止粉碎功能,相反,我想发送一条错误消息作为响应。

export const createUserTest = functions.https.onCall((data, context) => {
  const {email, password} = data;

  return new Promise((resolve, reject)=>{
    try{
      admin
           .auth()
           .createUser({
             email: email,
             emailVerified: false,
             password: password,
             disabled: false,
           })
           .then((user) => {
             resolve({
                 result: 'success',
                 user: user,
             }) ;
           })
           .catch((error) => {
             reject(error) ;
           });
    }catch(error) {
      reject (error)
    }  
  })  
});

我试图将功能放入try/catch阻止,但它没有帮助。你知道我怎样才能实现我的目标吗?

标签: javascriptfirebasegoogle-cloud-functions

解决方案


正如 Callable Cloud Functions 的文档中所解释的那样,“为确保客户端获得有用的错误详细信息,请通过抛出(或返回被拒绝的 Promise)实例从可调用对象中返回错误functions.https.HttpsError。”

该错误的code属性可以是此处列出的值之一。在您的情况下,最合适的似乎是already-exists.

另一方面,您会在此处找到Admin SDK 身份验证错误列表,并且您会看到如果提供的电子邮件已被现有用户使用,则错误代码为auth/email-already-exists

因此,您可以按如下方式调整您的代码:

export const createUserTest = functions.https.onCall((data, context) => {
    const { email, password } = data;

    return admin
        .auth()
        .createUser({
            email: email,
            emailVerified: false,
            password: password,
            disabled: false,
        })
        .then((user) => {
            return {
                result: 'success',
                user: user,
            }
        })
        .catch((error) => {
            if (error.code === 'auth/email-already-exists') {
                throw new functions.https.HttpsError('already-exists', 'The provided email is already in use by an existing user');
            } else {
                throw new functions.https.HttpsError('...other code....', '...');
                // If an error other than HttpsError is thrown, your client instead receives an error with the message INTERNAL and the code internal.
            }
        });

});

请参阅文档中的此处,如何在客户端处理错误。如果error.code == 'already-exists'您知道这是因为电子邮件已在使用中。


推荐阅读