简体   繁体   中英

How to perform a check for a particular FirebaseFirestore error code?

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?

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
    }
  }
}

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