如何处理Firebase管理员API调用错误?我应该抛出错误还是返回响应?而且我是否正确执行成功返回响应?
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,
}
}
});
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。但是您也可以像现在一样返回自己的错误代码。