0

Background: I come from the Python world where a try: / except: completely handles the exception, i.e. I can control what is being output when an exception is caught.

I am making an AJAX call to an API which may not be available:

function updateAPI() {
    getAPI()
            .done(function (r) {
                console.log('got API response: ' + JSON.stringify(r));
                updateFromAPI(r);
            })
            .fail(function (r) {
                console.log('failed to get API response: ' + r);
            }
            );
}

function getAPI() {
    return $.ajax({
        type: 'GET',
        url: 'http://127.0.0.1:8081/api'
    });
}

I was expecting to get one of my two messages sent to the console, and just that. The console, however, also shows the actual error, logged by JS:

Failed to load resource: net::ERR_CONNECTION_REFUSED (16:11:45:867 | error, network)
  at http://127.0.0.1:8081/api
failed to get API response: [object Object] (16:11:45:868)

Is this verbosity normal?

The second line shows that I caught the error (which I do not know how to display correctly yet).

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • JavaScript has try/catch and console.log(). But your code is not using exceptions and your console messages do not come from your console.log() calls. – Álvaro González Dec 10 '15 at 15:33
  • As pointed above this is Chrome outputting additional error info. In Firefox you won`t see the first file, just the .fail() text. – Petko Kostov Dec 10 '15 at 15:34

1 Answers1

0

According to the doc :

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown

By doing console.log('failed to get API response: ' + r); you're only logging the xhr Object (i.e. [object Object]).

Try:

.fail(function (r, textStatus, errorCode) {
    console.log('failed to get API response: ' + textStatus + '(error ' + errorCode + ')');
});
Community
  • 1
  • 1
pistou
  • 2,799
  • 5
  • 33
  • 60