Cannot use try-catch to catch exception from Client.RpcAsync in Unity

Hi,

sorry for noob question, but I tried to catch the exception on RpcAsync but not success.

my code

Debug.Log("#1. RpcAsync Start");
try
{
	result = await nakamaManager.Client.RpcAsync(nakamaManager.Session, apiname, payload);
	Debug.Log("#2. RpcAsync Finish");
}
catch (ApiResponseException exception)
{
	Debug.LogError("#3. RpcAsync Error. Code=" + exception.GrpcStatusCode + " Message=" + exception.Message);
	return;
}
Debug.Log("#4. End of try-catch block");

from the code above, I set payload to empty string to force the error and run.
It only shows debug text (#1. RpcAsync Start) and follow with error message “ApiResponseException: Error: Payload Empty. at APIName (index.js:868:5(52))”
The other debug text never appear on the console, even the debug text #4 is not showing up.

Could anyone please guide me how can I get this to work with try-catch block?
Thanks in advance for any answer & Best regards,
Bodin

Hey @bodin which HTTP adapter are you using? (In other words, can I see how you are creating the client?)

Hi lugehorsam,

sure, this is how I create client and login.

client = new Client(connectionData.Scheme, connectionData.Host, connectionData.Port, connectionData.ServerKey, UnityWebRequestAdapter.Instance);
 LoginAsync(connectionData, client.AuthenticateDeviceAsync(udid));

Hi lugehorsam,

sure, this is how I create client and login.

client = new Client(connectionData.Scheme, connectionData.Host, connectionData.Port, connectionData.ServerKey, UnityWebRequestAdapter.Instance);
 LoginAsync(connectionData, client.AuthenticateDeviceAsync(udid));

I think you’ll want to await on LoginAsync.

thank you very much for your reply.
sorry, but I have some confuse where to put await in LoginAsync.
This is the code in LoginAsync method. could you please guide where to implement that?

private async void LoginAsync(NakamaConnectionData connectionData, Task<ISession> sessionTask)
{
	try
	{
		session = await sessionTask;
	}
	catch (ApiResponseException exception)
	{
		Debug.Log(exception);
		onLoginFail?.Invoke(exception.Message);
		Debug.Log("Login Fail!");
		return;
	}

	Debug.Log("Session login Success!");

	socket = client.NewSocket(true);
	socket.Connected += Connected;
	socket.Closed += Disconnected;
	await socket.ConnectAsync(session);
	onLoginSuccess?.Invoke();
	Debug.Log("Socket connect Success!");
}

You want to await LoginAsync(...). So you await on the implicit Task returned by LoginAsync.

However it’s also best practice to return Task from LoginAsync.