【问题标题】:how do i handle the error for firebase cloud function api oncall?如何处理 firebase 云函数 api oncall 的错误?
【发布时间】:2020-10-03 09:47:47
【问题描述】:

如何处理 firebase admin api oncall 的错误?我应该抛出错误还是返回响应?而且我是否正确地进行了成功返回响应?

exports.registerVendor = functions.https.onCall(async (data, context) => {

    const email = data.email;
    const displayName = data.firstName + data.lastName;

    // Checking attribute.
    if (!(typeof email === 'string') || email.length === 0 || 
        !(typeof displayName === 'string') || displayName.length === 0) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
            'one arguments "text" containing the message text to add.');
    }

    // const uid = context.auth?.uid;

    // Checking that the user is authenticated.
    if (!context.auth) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('failed-precondition', 
            'The function must be called ' + 'while authenticated.');
    }

    try {
        const createResponse = await admin.auth().createUser({
            email: email,
            emailVerified: false,
            password: '123123',
            displayName: displayName,
            disabled: false
          })

        console.log(createResponse);

        return {
            data: {
                uid: createResponse.uid
            },
            status: 200,
            code: "Success"
        };
    } catch (err) {
        console.log(err as Error);
        // throw new functions.https.HttpsError(err.code, err.message);
        return {
            error: err,
        }
    }
});

【问题讨论】:

  • 如果此代码在可调用云函数中,请编辑您的问题以包含整个函数,以及您如何调用它。
  • 已注明,已更改。

标签: javascript firebase firebase-authentication google-cloud-functions firebase-admin


【解决方案1】:

handling errors 上的文档包含此示例:

// Checking attribute.
if (!(typeof text === 'string') || text.length === 0) {
  // Throwing an HttpsError so that the client gets the error details.
  throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
      'one arguments "text" containing the message text to add.');
}
// Checking that the user is authenticated.
if (!context.auth) {
  // Throwing an HttpsError so that the client gets the error details.
  throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
      'while authenticated.');
}

因此,这是从服务器向调用者获取错误条件的推荐方法,然后您将使用handle them on the client。但是您也可以像现在一样返回自己的错误代码。

【讨论】:

  • 如前所述,文档推荐了另一种方式。但如果你所拥有的对你有用,我觉得它很好。
猜你喜欢
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2020-12-01
  • 2018-05-17
  • 2018-12-06
  • 2018-12-16
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多