Reputation: 478
I am calling a API using the below code...
public async Task<Dictionary<string, string>> GetDataAsync()
{
try
{
var url = "https://address.com/myapi";
var request = new RestRequest(url, Method.GET) { Timeout = 5000 };
request.AddAuthenticationHeaders();
var response = await _client.ExecuteTaskAsync(request);
return ProcessResponse(response);
}
catch (Exception e)
{
throw new MyApplicationException(e.Message, e.InnerException, AlertCode.UnknownError);
}
}
above is called by:
public async Task GetData()
{
data= await webCaller.GetDataAsync();
}
this code handles all the errors and shows the proper popup and app continues but only on this particular error the app is crashing
System.Net.WebException: Error: ConnectFailure (Network is unreachable) ---> System.Net.Sockets.SocketException: Network is unreachable
I reproduce this error by calling the API and switching off the connection, so obviously the network wont be reachable.
In my Activity I handle the exception here
protected virtual void OnException_Occured(object sender, RaiseThrowableEventArgs e)
{
RunOnUiThread(
() =>
{
ExceptionPopup.Popup = new CommonPopup(this, ExceptionHelper.GetUserFriendlyMessage(e.Exception));
ExceptionPopup.Popup.Show();
});
}
ReportError(e.Exception);
e.Handled = true;
}
OnResume:
protected override void OnResume()
{
base.OnResume();
AndroidEnvironment.UnhandledExceptionRaiser += OnException_Occured;
}
OnPause:
protected override void OnPause()
{
base.OnPause();
AndroidEnvironment.UnhandledExceptionRaiser -= OnException_Occured;
}
Upvotes: 3
Views: 2146
Reputation: 11
Does it crash every time you call GetData()
, or it crashes randomly?
I ran into a similar problem today where my async API call makes the iOS app crash randomly. I'm not certain if my problem is relevant to yours but I'll explain what I did in case it helps you.
In my case, the problem turned out not have anything to do with the connection. For some reason, the API call is not always successful, when it fails, it returns null to my variable, which cause an "object not set to an instance of an object" error later on. Since I can't guarantee that every time my API call returns a non-null value, what I did is putting the API call in a while loop and check if I get a null.
Here's my code example:
Message[] allMessages;
while(allMessages==null)
{
allMessages = await Message.GetAsync();
}
Upvotes: 1