'How to handle net::ERR_CONNECTION_REFUSED in jquery ajax

I have this kind of javascript:

$.ajax({
    url: "//myapi.com/json",
    dataType: "jsonp"
}).done(function (data) {
    selectText('Id', data.country);
}).fail(function (jqXHR, textStatus, errorThrown) {
    var defaultOption = 'US'
    selectDropdownByText('Id', defaultOption);

    console.log(errorThrown);
});

But the thing is that on https request my ajax is not working because service I am calling is not accessible via https and I am getting error :ERR_CONNECTION_REFUSED - so that is fine, I just want to handle that. I have .fail in ajax call, but it is not handling :ERR_CONNECTION_REFUSED Could you give advice on how to handle :ERR_CONNECTION_REFUSED in that case?

I also was trying to wrap my ajax call to try-catch block, but it wasn't working either.



Solution 1:[1]

You can use timeout property of $.ajax to fire the error callback.

This will make sure that the error callback is fired if the server doesn't respond within a particular time limit.

$.ajax({
    url: "//myapi.com/json",
    dataType: "jsonp",
    timeout: 15000 // adjust the limit. currently its 15 seconds
}).done(function (data) {
    selectText('Id', data.country);
}).fail(function (jqXHR, textStatus, errorThrown) {
    var defaultOption = 'US'
    selectDropdownByText('Id', defaultOption);

    console.log(errorThrown);
});

This will trigger the fail callback when there is no internet as well.

Solution 2:[2]

It appears that when jqXHR.readyState (i.e., the readyState field of the first parameter to the $.ajax(...).fail() method) is 0 that a network error has occurred. However, I have not been able to ascertain what the exact network error is via JavaScript.

I have looked at the jQuery Ajax code, and xhr.send() (i.e., the XMLHttpRequest.send()) method (which generates the network error) does not catch nor throw the error. Thus, it is not possible to catch it.

It appears that the browser detects and displays the correct error message but that jQuery is oblivious to the specific type of network error that occurs.

Solution 3:[3]

So, fail is being called if we get a ERR_CONNECTION_REFUSED, but there is no way to actually see why fail is being called. Is there a way to detect inside of the fail method why things failed? i.e. timeout vs connection refused? There is a difference between the two. One I could possible retry, the other makes no difference.

You do not need to set timeout to handle connection refused failures.

Solution 4:[4]

    <code>$.ajax({
         url: "//myapi.com/json", //this is problem
         dataType: "jsonp"
    }).done(function (data) {
         selectText('Id', data.country);
    }).fail(function (jqXHR, textStatus, errorThrown) {
        var defaultOption = 'US'
        selectDropdownByText('Id', defaultOption);

        console.log(errorThrown);
    });</code>

relative path is not good,

 <code>$.ajax({
        url: "myapi.com/json", //this will work
        dataType: "jsonp"
    }).done(function (data) {
        selectText('Id', data.country);
    }).fail(function (jqXHR, textStatus, errorThrown) {
        var defaultOption = 'US'
        selectDropdownByText('Id', defaultOption);

        console.log(errorThrown);
    });</code>

Solution 5:[5]

If you use this fail function it will get caught in the jqXHR.status===0 condition.

        .fail(function (jqXHR, exception) {
            // Our error logic here
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'No connection.\n Verify Network.';
                //ERR_CONNECTION_REFUSED hits this one
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
             $('#info').html("<p class='alert alert-danger msg'>Error: " + msg + "</p>");
        })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mohamedrias
Solution 2 Darwin Airola
Solution 3 Mike Cluck
Solution 4 user9330552
Solution 5 JoeKincognito