Firebase CloudFunction不会在Promise中返回错误

时间:2019-11-26 06:41:54

标签: node.js firebase firebase-authentication google-cloud-functions

使用Firebase Cloudfunctions和带有nodeJS的Admin SDK创建用户时,我尝试获取错误。

创建用户时,一切正常,因为创建的用户返回了我,但是创建错误时,我没有得到应有的错误。

因此,在前端方面,从来没有收到任何东西,好像它是正确的一样

示例:我没有输入电子邮件来创建新用户,并且请求的状态为200,但答案是:

{“ result”:{“ errorInfo”:{“ code”:“ auth / invalid-password”,“ message”:“密码必须是至少包含6个字符的字符串。”},“ codePrefix“:” auth“}}

这是我的函数代码:

exports.addNewUser = functions.https.onCall((data, context) => {
    return admin.auth().createUser({
      email: data.email,
      emailVerified: true,
      password: data.password,
      displayName: data.name,
      disabled: false
    }).then(userRecord => {
        console.log('Successfully created new user:', userRecord.uid);
        return userRecord;
      })
      .catch( error => {
        console.log('Error creating new user:', error);
        return error;
      });
  });

这在创建用户时可以很好地工作,但如果存在错误,则错误不会再次出现。

我所做的是,不是返回错误,而是仅返回字符串,并且如果字符串正确返回,则

1 个答案:

答案 0 :(得分:2)

这是因为要处理Callable Cloud Function中的错误,您需要抛出functions.https.HttpsError,如documentation中所述。

因此以下内容将起作用:

exports.addNewUser = functions.https.onCall((data, context) => {
    return admin.auth().createUser({
        email: data.email,
        emailVerified: true,
        password: data.password,
        displayName: "dataname",
        disabled: false
    }).then(userRecord => {
        console.log('Successfully created new user:', userRecord.uid);
        return userRecord;
    })
    .catch(error => {
        console.log('Error creating new user:', error);
        throw new functions.https.HttpsError('invalid-argument', error.message);
    });
});

还请注意文档中的section,了解如何处理客户端错误。