[英]How can I send a custom response from a firebase cloud function?
[英]How to prevent Firebase Cloud Function from crashing and how to send error message as response?
我創建了一個簡單的createUser
function,它在調用時執行。 我有一個問題。 當用戶嘗試向已經存在的 email 注冊時,function 崩潰。 我的意思是,沒關系,因為沒有人希望有 2 個用戶具有相同的 email 地址,但我想防止破壞 function,相反,我想發送一條錯誤消息作為響應。
export const createUserTest = functions.https.onCall((data, context) => {
const {email, password} = data;
return new Promise((resolve, reject)=>{
try{
admin
.auth()
.createUser({
email: email,
emailVerified: false,
password: password,
disabled: false,
})
.then((user) => {
resolve({
result: 'success',
user: user,
}) ;
})
.catch((error) => {
reject(error) ;
});
}catch(error) {
reject (error)
}
})
});
我試圖將 function 放入try/catch
塊,但沒有幫助。 你知道我怎樣才能實現我的目標嗎?
如可調用雲函數的文檔中所述,“為確保客戶端獲得有用的錯誤詳細信息,請通過拋出(或返回被拒絕的 Promise 拒絕) functions.https.HttpsError
實例從可調用返回錯誤。https.HttpsError ”。
該錯誤的code
屬性可以是此處列出的值之一。 在您的情況下,最合適的似乎是already-exists
。
另一方面,您會在此處找到管理員 SDK 身份驗證錯誤列表,並且您會看到如果提供的 email 已被現有用戶使用,則錯誤代碼為auth/email-already-exists
。
因此,您可以按如下方式調整您的代碼:
export const createUserTest = functions.https.onCall((data, context) => {
const { email, password } = data;
return admin
.auth()
.createUser({
email: email,
emailVerified: false,
password: password,
disabled: false,
})
.then((user) => {
return {
result: 'success',
user: user,
}
})
.catch((error) => {
if (error.code === 'auth/email-already-exists') {
throw new functions.https.HttpsError('already-exists', 'The provided email is already in use by an existing user');
} else {
throw new functions.https.HttpsError('...other code....', '...');
// If an error other than HttpsError is thrown, your client instead receives an error with the message INTERNAL and the code internal.
}
});
});
請參閱文檔中的此處,如何在客戶端處理錯誤。 如果error.code == 'already-exists'
你知道這是因為 email 已經在使用中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.