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)
}
}
}
2
Answers
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: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.
I would avoid "checking" to see if a collection exists or doesn’t, unless if there is a good and specific reason to. If there isn’t, then simply query the documents you need and if you get them you get them and if you don’t you don’t; springboard from there.
As to your error, a do-try-catch approach is not the solution I’d use here because that sort of error handling should be reserved for things out of your control, like network tasks. Your specific error is completely in your control because you’ve constructed an illegal document path. You can, and should, safeguard against this by simply ensuring the strings you pass into the path are valid, which is always best practice if there’s a chance they can be
nil
.Furthermore, deleting the documents from this collection and the error you’re receiving appear to be coincidental, unless if there is code elsewhere that’s constructing this document path based on the existence of documents in this collection. If there isn’t (and there probably shouldn’t) then this is just a coincidence.