Home > OS >  How to perform a check for a particular FirebaseFirestore error code?
How to perform a check for a particular FirebaseFirestore error code?

Time:05-27

I have the following code:

db.collection("property").document(userUID).update(propertyRoot).addOnSuccessListener(
                new OnSuccessListener<Void>(){
                    @Override
                    public void onSuccess(Void aVoid)
                    {
                        //Success
                    }
                }
        ).addOnFailureListener(
                new OnFailureListener(){
                    @Override
                    public void onFailure(@NonNull Exception e){
                        //Create a new collection and set
                    }
                }
        );

I would like to update my Firestore database if the collection already exists. Otherwise, I would like Firestore to create a new collection.

I would like to create a new collection only if the collection is not found. Essentially, I would like to do the check like this:

db.collection("property").document(userUID).update(propertyRoot).addOnSuccessListener(
                    new OnSuccessListener<Void>(){
                        @Override
                        public void onSuccess(Void aVoid)
                        {
                            //Success
                        }
                    }
            ).addOnFailureListener(
                    new OnFailureListener(){
                        @Override
                        public void onFailure(@NonNull Exception e){
                            if(e.errorCode == FirebaseFirestoreException.NOT_FOUND)
                            {
                                //Create a new collection and set
                            }
                        }
                    }
            );

How can I go about achieving this?

CodePudding user response:

That should be possible if you cast the exception to a feedbackFirebaseFirestoreException object and then check its getCode() value against the possible Firestore error codes.

So something like:

public void onFailure(@NonNull Exception e){
  if (e is FirebaseFirestoreException) {
    if ((e as FirebaseFirestoreException).getCode() == FirebaseFirestoreException.Code.NOT_FOUND)
    {
        //Create a new collection and set
    }
  }
}
  • Related