Matthew Flynn
Matthew Flynn

Reputation: 3941

WebApi Catch Connection Timeout Error

I have a C# project connected to a WebApi 2.0.

Now the application is to be used on tablets using a 3G data connection.

I want to catch and output a friendly message informing them the application cannot contact the server and that they please ensure they have a 3g connection.

What is the best way to do this please?

Normally the calls to load the views are made using a javascript post;

$.post('@Url.Action("Action", "Controller")',

which I catch in the fail event;

.fail(function (xhr, textStatus, errorThrown) {
    // if connection issue then display an error message
})

I have also had to 'hide' the webapi endpoint to stop url hacks etc exposing it. So the call is actually made to the application mvc controller action, before which then invokes the api method.

I catch any errors in here as follows;

catch (HttpResponseException ex)
{
    var msg = ex.Response.Content.ReadAsStringAsync().Result;
    var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
    return new HttpStatusCodeResult(500, errorModel.errormessage);
}
catch (Exception ex)
{
    return new HttpStatusCodeResult(500, ex.Message);
}

Where the AcknowledgeModel is a exception filter which wraps the error in their specified model.

Upvotes: 0

Views: 2540

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

Timeout is a client-side error. Server will never tell you that connection is timed out - you will get the response or a request will actually timeout.

So, the solution is to use client-side handlers.
For jQuery AJAX you handle it using .fail().
According to jQuery AJAX documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

So, you can easily do it this way:

$.ajax({
    url: 'example.com',
    data: { }
}).done(function(r) {

}).fail(function(xhr, t, err) {
    if (t === "timeout") {
        alert("The connection has timed out. Please, check data connection availability");
    } else { 
        alert("Unknown server error. We are sorry!");
    }
});

Upvotes: 1

Related Questions