Home > Net >  do catch to fix firebase "document path cannot be empty"
do catch to fix firebase "document path cannot be empty"

Time:12-22

I have a function to fetch convos and it worked but then I deleted all the documents in firebase. So now when I run it, it sais "document path cannot be empty" and the app crashes. Im am not very familiar with swift but in python I simply just use a try and except. In the try block I can simply copy and paste all my code, and the except block I jus do my error handeling. Im not sure how to do this in swift for my entire function. Can anyone show how I can rearrange my function so that the function body is inside a do/try block. Also what is the most strategic spot to do my error handeling, the viewModel file or the Service file? the viewModel file inherits functions from the service file

viewModel file

    func fetchConvos(){
        var userList: [User] = []
        service.getConversations() { users in
            userList = users
            userList.forEach { user in
                var messList: [Message] = []
              }

        }
    }

service file

    func getConversations(completion: @escaping([User]) -> Void){

            Firestore.firestore().collection("users")
                .document(uid)
                .collection("user-convo")
                .getDocuments { snapshot, _ in
                    guard let documents = snapshot?.documents else { return }
                    
                    documents.forEach { doc in
                        let userID = doc.documentID
                        
                        users.append(userID)
                        completion(users)
                            
                        
                    }
                }
        
    }

CodePudding user response:

Trying to handle an exception as flow control is a bad idea here. See for an explanation why that is: Why not use exceptions as regular flow of control?

So instead of handling the exception that you get when uid is null or empty, check whether it has a value first and then only call the Firestore API with it if it has a value. For example:

if !(uid ?? "").isEmpty {
    Firestore.firestore().collection("users")
        .document(uid)
        .collection("user-convo")
        ...
}

There is no specific operation to check whether a collection exists.

Instead collection is comes into existence when you add the first document to it, and disappears when you remove the last document from it.

So to check whether a collection exists, the simplest way is to try and read a single document from it.

Firestore.firestore().collection("users")
    .document("theUID")
    .collection("user-convo")
    .limit(to: 1) //            
  • Related