Reputation: 872
I am trying to use firebase cloud functions for the backend of a webapp. I have tried to create a function that creates a user as follows:
exports.createUser = functions.https.onCall(async (data, context) => {
//validate email
if (!verifyEmail(data.email))
throw new functions.https.HttpsError("invalid-argument", `The email ${data.email} is not formatted correctly`)
if (data.password !== data.confirmPassword)
throw new functions.https.HttpsError("invalid-argument", `Passwords do not match`)
if (!data.username)
throw new functions.https.HttpsError("invalid-argument", `Username cannot be empty`)
admin.auth().createUser({
email: data.email,
password: data.password
}).then(user => {
admin.firestore().collection('users').doc(user.uid).set({
username: data.username
}).catch(error => {
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`, error)
})
}).catch(error => {
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`, error)
})
})
When an incorrectly formatted email is passed in, the error is passed onto the user, however, when a failure occurs on the creation of a user the error is printed out on the backend logs, and not sent to the user. Is there a way I can fix this?
Upvotes: 0
Views: 26
Reputation: 26313
You're mixing async
/await
with .then()
which is not something that is generally recommended as it leads to this kind of confusion. Try something like this:
exports.createUser = functions.https.onCall(async (data, context) => {
//validate email
if (!verifyEmail(data.email))
throw new functions.https.HttpsError("invalid-argument", `The email ${data.email} is not formatted correctly`)
if (data.password !== data.confirmPassword)
throw new functions.https.HttpsError("invalid-argument", `Passwords do not match`)
if (!data.username)
throw new functions.https.HttpsError("invalid-argument", `Username cannot be empty`)
try {
const user = await admin.auth().createUser({
email: data.email,
password: data.password
});
await admin.firestore().collection('users').doc(user.uid).set({
username: data.username
});
} catch (err) {
functions.logger.error("Unexpected error creating user", err);
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`);
}
})
Upvotes: 1