Joris Meylaers
Joris Meylaers

Reputation: 83

Xamarin Forms: ModernHttpClient errorhandling in PCL

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.

Upvotes: 2

Views: 1024

Answers (2)

Elte Hupkes
Elte Hupkes

Reputation: 2978

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.

Upvotes: 0

Steven Thewissen
Steven Thewissen

Reputation: 2981

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

Upvotes: 1

Related Questions