Nescio
Nescio

Reputation: 513

Catching error during api call not working?

I'm trying to make an API call to ip-api.com/json, but from what I understand it is being blocked by ad-blockers. As such I wanted to add a try-catch to see when it fails so that I can solve this in another way, but the script doesn't seem to go into the catch block, and instead it just throws the error.

Is there a way to catch the exception thrown here?

$(document).ready(function() {

    try {
        /* Try getting the request with the required parameters
            Otherwise use default ones */
        jQuery.getJSON(API_Location, "", function(position) {
            if (position.lat && position.lon) {
                updateWeather(position);
            } else {
                updateWeather({"lat":DEFAULT_LAT, "lon":DEFAULT_LON});
            }
        });
    } catch(err) {
        /* TODO display warning message */
        console.log('option b');
        updateWeather({"lat":DEFAULT_LAT, "lon":DEFAULT_LON});
    }
});

The catch block is never being triggered and instead it throws an exception:

jquery.min.js:4 GET http://ip-api.com/json net::ERR_BLOCKED_BY_CLIENT

Upvotes: 2

Views: 808

Answers (1)

nisar
nisar

Reputation: 1065

use default done,fail to trigger error.

API_Location=' http://ip-api.com/json1';
        $.getJSON( API_Location)
          .done(function( position ) {
              if (position.lat && position.lon) {
                updateWeather(position);
            } else {
                updateWeather({"lat":DEFAULT_LAT, "lon":DEFAULT_LON});
            }
          })
          .fail(function( jqxhr, textStatus, error ) {
            var err = textStatus + ", " + error;
            console.log( "Request Failed: " + err );
        });

Upvotes: 1

Related Questions