Reputation: 807
I have two references like:
var receiverMaleRef = admin.database().ref(`root/users/male/${currentUser}`);
var receiverFemaleRef = admin.database().ref(`root/users/female/${currentUser}`);
'currentUser' is unique overall i.e same name cannot exists on both nodes.
And I am using following code to get values:
return receiverMaleRef.once('value').then(function(maleDataSnapshot) {
})
.catch(err => {
//if currentUser is not male catch should be called because of invalid reference
//Get value from female node
return receiverFemaleRef.once('value').then(function(dataSnapshot) {
})
});
The problem I am facing is if 'currentUser' is female it does not catches the error, instead it returns null in maleDataSnapshot.
What should be the workaround this issue?
Upvotes: 0
Views: 65
Reputation: 83181
If you want to catch the fact that maleDataSnapshot
is null (i.e. does not exist) with your code you could use the exists()
method and do as follows:
return receiverMaleRef.once('value').then(function(maleDataSnapshot) {
if (!maleDataSnapshot.exists()) {
throw new Error('currentUser is not male');
}
})
.catch(err => {
//if currentUser is not male catch should be called because of invalid reference
//Get value from female node
return receiverFemaleRef.once('value').then(function(dataSnapshot) {
})
});
However it is not really recommended to use error catching in order to implement your business logic. You may refactor your Cloud Function code with if/then/else. It is difficult to give an advice on how to do that without seeing the full code of the Cloud Function (i.e. overall logic, trigger type, what does it return at the end, etc.).
Upvotes: 1