Javascript 我是否需要使用firebase函数api将抛出放在try-catch块中才能捕获它?

Javascript 我是否需要使用firebase函数api将抛出放在try-catch块中才能捕获它?,javascript,node.js,firebase,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Functions,我需要把球放在试接球区内才能接住吗? 我正在使用firebase函数api // 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', '

我需要把球放在试接球区内才能接住吗? 我正在使用firebase函数api

// 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 {
    await updateCustomerAccount(context.auth.uid, customer.id)

    return {
        status: 200,
    };
} catch (err) {
    console.log(err as Error);
    return {
        error: err.errorInfo,
        status: 500,
    }
}

是的,您确实需要将throw关键字放在try块中。
try
catch
块仅在try块内捕获错误

throw语句抛出用户定义的异常。当前函数的执行将停止(throw之后的语句将不被执行),控制权将传递给调用堆栈中的第一个catch块如果调用方函数之间不存在catch块,程序将终止。


在这种情况下,不需要您的
throw
进入try/catch。如果希望函数终止时调用代码中出现有意义的错误,则需要允许该异常从函数的顶层传播出去,以便云函数SDK可以处理该异常,并将其转换为HTTP错误,以便客户端接收。如果将其放在try/catch中,则该函数将不会为客户端应用生成正确的错误代码和消息


此外,如果您的可调用函数需要客户端身份验证,那么您应该使用“未经身份验证”错误代码,而不是“失败的前提条件”代码。据我所知,如。

是中所述。在本例中,情况并非如此。异常需要传播到函数之外,以便SDK(Firebase的云函数)能够捕获它并发送适当的响应。将其放入try/catch将抑制错误,并且函数将无法正常工作。OP应该显示更多代码,以使这种情况更加清楚。