简体   繁体   中英

firebase firestore - how to check an error in the catch

I want to catch a firestore error and execute code based on what kind of error it is. (My database is build that if a document doesn't exist you won't be able to access it and therefore I have been getting a lot of permission-denied errors for non-existent documents. My solution is to check the error and create a document if I get a permission denied error.)

This is my current code:

            userDataDocRef.collection('emailPreferences').doc('main').get().then(function(doc) {
          if (doc.exists) {
            var data = doc.data();
            console.log(data);
            var getGameUpdates = data.getGameUpdates;
            switchEmailNewGames.checked = getGameUpdates;
          } else {

          }
        }).catch(function(error) {
          console.log(error)
          if (error == firebase.firestore.FirestoreError.permission-denied) {
            console.log('FIREBASE PERMISSION DENIED ERROR')
          }
        })

My Question: How do I check what kind of error I got properly? (what I have at the moment doesn't work)

Thank you for your help!

There is no way to determine from the response what specific security rule failed. This is by design, since exposing this information would give malicious users access to important information about how your database is secured. That's why the error message sent to the client is always a generic "permission denied".

In general depending on error message like this for regular flow control sounds like an antipattern. If you only want to create a document if it doesn't exist, perform the check in a transaction, which ensures the check and create happen atomically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM