2

My app connects to an api which requires an HTTPS-connection.
ModernHttpClients (NativeMessageHandler) works fine until an exception is thrown...
When there is no wifi available, an UnknownHostException is thrown on Android. Is it possible to make a catch that works on both Android and iOS? UnknownHostException is in the Java.Net library which can't be used in the iOS project.

2 Answers2

1

You can use the ConnectivityPlugin in your shared Xamarin Forms code to check for an internet connection before doing your request.

Steven Thewissen
  • 2,971
  • 17
  • 23
  • Not really a great solution considering all the other errors that may be thrown, for instance when there is in fact a mobile connection but it's flaky. The fact that there's a connection when you start doing your stuff is absolutely no guarantee that it'll stay there while your doing your stuff. – Elte Hupkes Jun 09 '17 at 09:53
  • Absolutely true, but the same component also exposes events that handle when the connectivity changed so you can hook in to those to handle situations like the one you're describing. – Steven Thewissen Jun 09 '17 at 12:23
  • That's hardly useful if your connection drops while you're performing a request. I'm not saying that you shouldn't check for connection - you should, and it prevents a lot of problems. I'm just saying that this doesn't at all rid you of the need to perform connection exception handling. – Elte Hupkes Jun 09 '17 at 13:39
0

Personally I'm using a cross platform interface to handle network errors. You can for instance have something like (using MvvmCross in this example):

try
{
    var client = new HttpClient();
    var result = await client.GetAsync("http://some-url.com");
}
catch (Exception e)
{
    var platformErrorChecker = Mvx.Resolve<IPlatformNetworkError>();
    if (platformErrorChecker.IsNetworkError(e))
    {
        // Handle network error
    }
    else
    {
        // Other exception, just throw
        throw;
    }
}

And a service defined as:

public interface IPlatformNetworkError
{
    bool IsNetworkError(Exception e);
}

Which you implement on each platform specifically, or only where needed. This is a simple example of course, you can have each platform provide more information about their specific network errors.

Elte Hupkes
  • 2,773
  • 2
  • 23
  • 18