Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase admin sdk calling the wrong catch

I am trying to add a new user with firebase-admin and then to save a new document in a custom collection.

Sample code following:

admin.auth().createUser(user)

    .then((record) => {

       user.uid = record.uid;

       userCollection.doc(record.uid).set({...user})

           .then(writeResult => {
               resolve();
           })
           .catch(reason => {
               reject(reason)
           });
    })
    .catch((err) => {
        reject(err);
    });

The problem is, if the userCollection.doc(record.uid).set({...user}) fails, I expect the nested catch (with reason as param) to be called. Instead, always the outer one is called (with err as param).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there something wrong with the SDK or am I doing something wrong?

Thank you

>Solution :

This is because you don’t return the promise returned by userCollection.doc(record.uid).set() and therefore you don’t return the promises returned by the subsequent then() and catch() methods. In other words you don’t return the promises chain.

But, actually, you should chain your Promises as follows and avoid a then()/catch() pyramid.

  admin
    .auth().createUser(user)
    .then((record) => {
      user.uid = record.uid;

      return userCollection
        .doc(record.uid)
        .set({ ...user })
    })
    .catch((err) => {

      // Here you catch the potential errors of 
      // the createUser() AND set() methods

      console.log(JSON.stringify(err));

    });

More details here, here and here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading