Something wrong with this try / catch block?

Code reaches the error throwing part, showing a pop up alert(“player not found”); when expected.
Console also indicates that the error is thrown, but not caught: util.ts:598 Uncaught Error: PLAYER NOT FOUND
The catch block never happens. Is something wrong here?

Thanks for the help

	try 
	{			
		firebase.database().ref().orderByChild('name').equalTo(path).limitToLast(1).on("value", function(snapshot) 
		{
			if (!snapshot.val()) { alert("player not found"); throw new Error("PLAYER NOT FOUND"); }
			
			snapshot.forEach(function(data) 
			{
				datablob = data.val().name.slice(0,10) + "|" + data.val().score;
				unityInstance.Module.SendMessage(objectName, callback, datablob);	
			});
		});
	}
	catch(error)
	{
		alert("Error-caught BEGIN");
		unityInstance.Module.SendMessage(objectName, fallback, "Error: " + error.message);
		alert("Error-caught END");
	}

Hi @resurrectedsock, the firebase data retrieval is event based, meaning the on('value') callback is getting executed asynchronously; and by the time you’re throwing the error, the control flow has already left the try / catch block. So you have to catch the error inside the function where you’re throwing it – consider this simple example:

try {
  // Will get caught immediately
  throw new Error('error 1')
} catch (e) {
  console.log('caught', e)
}

setTimeout(function () {
  try {
    // Will get caught when the callback
    // gets called after 1 second
    throw new Error('error 2')
  } catch (e) {
    console.log('caught', e)
  }
}, 1000)

try {
  setTimeout(function () {
    // Will never get caught
    throw new Error('error 3')
  }, 1000)
} catch (e) {
  console.log('caught', e)
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.