抛出新函数。Firebase Cloud上的https.HttpsError函数被拒绝为客户端上的内部错误

时间:2018-06-19 20:26:32

标签: javascript reactjs firebase google-cloud-functions

我已将以下Cloud Function部署到我的Firebase项目中:

exports.createCredentials = functions.https.onCall((data, context) => {
    if(!context.auth)
        throw new functions.https.HttpsError('failed-auth', 'You must be authenticated to call this function')

    const { email, password } = data;

    if(!(typeof email === 'string'))
        throw new functions.https.HttpsError('invalid-email', 'Email must be a string')
    if(!(typeof password === 'string'))
        throw new functions.https.HttpsError('invalid-password', 'Password must be a string')

    return admin.auth().createUser({
        email,
        password
    })
    .then(userRecord => {
        return { userRecord }
    })
    .catch((error) => { 
        throw new functions.https.HttpsError(error.code, error.message)
    })
})

问题是,每当我抛出一个新的functions.https.HttpsError而不是在客户端以docs状态捕获错误时,我都会得到一个internal错误代码。在函数的日志中,当我尝试调用HttpsError时,它显示了未处理的错误。这是日志的示例:

Unhandled error Error: Unknown error status: auth/email-already-exists
    at new HttpsError (/user_code/node_modules/firebase-functions/lib/providers/https.js:80:19)
    at admin.auth.createUser.then.catch (/user_code/index.js:26:9)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我知道,如果没有抛出HttpsError,这种类型的函数将拒绝内部错误,但据我所知,函数中的情况并非如此。我正在React中编写前端程序,所以这就是我所说的firebase函数的方式:

let options = {
    email: arquitect.email,
    password: arquitect.password
}

let createCredentials = firebase.functions().httpsCallable('createCredentials')
createCredentials(options)
    .then(result => {

    })
    .catch(error => console.log(error))

有什么我想念的吗?

3 个答案:

答案 0 :(得分:7)

根据您链接的文档,看来您没有使用functions.https.HttpsError中列出的代码参数值。该值必须是Google API的规范错误代码之一。例如,此处未列出“验证失败”或“无效电子邮件”。您可以改用“权限拒绝”或“无效参数”。

答案 1 :(得分:3)

我有同样的问题。新手在这里,所以我的尝试可能是错误的,但是我在本地调用函数,而无法进入HttpsError

因此,请执行以下操作:

const functionsGlobal = require('firebase-functions')
const functions = functionsGlobal.region('europe-west2')

然后我必须像这样获得HttpsError

throw new functionsGlobal.https.HttpsError('failed-precondition',
    'The function must be called while authenticated.', 'hello')

代替:

throw new functions.https.HttpsError('failed-precondition', 
    'The function must be called while authenticated.', 'hello')

现在可以使用,但我希望有人能解释原因。

答案 2 :(得分:0)

我自己的问题只是ctheprinter所说的区域

完整的工作示例:

const firebaseFunctions = require('firebase-functions');
const functions = firebaseFunctions.region("europe-west1");

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

    if(!context.auth)
        throw new firebaseFunctions.https.HttpsError('failed-auth', 'You must be authenticated to call this function')

})