25

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.

mikhail
  • 5,019
  • 2
  • 34
  • 47
Sergino
  • 10,128
  • 30
  • 98
  • 159

5 Answers5

7

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.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • So there is no onther way around? Do u have any ideas why `try-cath` is not handling that eror? `try {$.ajax({ ... });} catch(ex) {}` – Sergino Apr 04 '15 at 00:37
  • 2
    I can confirm that there is no way to catch this kind of issue without explicitly setting timeout attribute. another way can be to check the data value in the success handler, and if it's empty do something similar to the errore handler: http://stackoverflow.com/a/6792515/615924 – rvandoni Jun 15 '15 at 09:09
  • 1
    In my case setting the timeout still results in `net::ERR_CONNECTION_REFUSED` and `fail` not being run. Is there some other condition that needs to be met? – dlsso Oct 22 '15 at 16:56
  • 2
    @sreginogemoh About try{}catch blocks, they are useful for synchronous code. With Asynch ajax calls the code is run and the callbacks registered. Those are fired after a few seconds without blocking the rest of your code so your try{}catch block already finished running by the time the http promise object is fulfilled or rejected. – SparK Jun 15 '16 at 17:37
  • @mohamedrias: i dig this topic, but i have the same issue. I tried to use timeout , but : it failt before the timeout and still have the error log message. The .fail() is triggered, so it's a 50% win. – J.Mengelle Jun 24 '20 at 09:31
3

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>");
        })
JoeKincognito
  • 321
  • 1
  • 9
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.

Darwin Airola
  • 919
  • 8
  • 11
0

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.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
BradW
  • 53
  • 5
  • If you "fail" for a timeout, the "error" parameter of the function will be "timeout" and not "error" – Claudio Jan 24 '16 at 11:01
0
    <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>