17

I an using javascript and am getting an message that I have exceeded my daily request quota for this API. Is there a way to capture this error message in a try catch block so when I go over my quota I can execute another piece of code. I have seen several similar posts, but nothing that has been helpful. Here is my code.

(function (window, google, lat, lng) {
           var options = {
               center: {
                   lat: Number(lat),
                   lng: Number(lng)
               },
                 zoom: 5,
                 disableDefaultUI: true,
                 scrollwheel: true,
                 draggable: false
           },
           element = document.getElementById('map-canvas')
           var map = new google.maps.Map(element, options)
       }(window, window.google, result[i]['latitude'], result[i]['longitude']));
Aaron
  • 4,380
  • 19
  • 85
  • 141

3 Answers3

11

Update As per the documentation:

if you want to programmatically detect an authentication failure (for example to automatically send an beacon) you can prepare a callback function. If the following global function is defined it will be called when the authentication fails. function gm_authFailure() {//code}

Here is a list of errors that the gm_authFaliure function should be able to catch. It also mentions a OverQuotaMapError error.

As per the documentation:

if too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code.

So you should check the response code. If the Google maps javascript library does not allow to access to the response code then I recommend making a HTTP request to the API to get the response code.

function initMap(window, google, lat, lng) {
   var options = {
       center: {
           lat: Number(lat),
           lng: Number(lng)
       },
       zoom: 5,
       disableDefaultUI: true,
       scrollwheel: true,
       draggable: false
   },
   element = document.getElementById('map-canvas'),
   map = new google.maps.Map(element, options);
};

function googleMapsCustomError(){
    alert('Google Maps custom error triggered');
}

// if you want to respond to a specific error, you may hack the
// console to intercept messages.
// check if a message is a Google Map's error message and respond
// accordingly
(function takeOverConsole() { // taken from http://tobyho.com/2012/07/27/taking-over-console-log/
    var console = window.console
    if (!console) return

    function intercept(method) {
        var original = console[method]
        console[method] = function() {
           // check message
           if(arguments[0] && arguments[0].indexOf('OverQuotaMapError') !== -1) {
             googleMapsCustomError();
           }
           
            if (original.apply) {
                // Do this for normal browsers
                original.apply(console, arguments)
            } else {
                // Do this for IE
                var message = Array.prototype.slice.apply(arguments).join(' ')
                original(message)
            }
        }
    }
    var methods = ['error']; // only interested in the console.error method
    for (var i = 0; i < methods.length; i++)
        intercept(methods[i])
}())
<!DOCTYPE html>
<div id="map-canvas"></div>

<script>
// Notice i am defining this within my html file, just to be sure that this function exists before the Google Maps API is loaded.
window.gm_authFailure = function() {
    // remove the map div or maybe call another API to load map
   // maybe display a useful message to the user
   alert('Google maps failed to load!');
}

window.showMap = function() {
  var lat = -34.397,
      lng = 150.644;
  initMap(window, window.google, lat, lng);
};
</script>

<!-- We are passing an invalid API key. Also notice that we have defined 'callback' as 'showMap' which means that when the Google API JavaScript library is finished loading it will call the 'showMap' function. -->
<script src="https://maps.googleapis.com/maps/api/js?key=INVALID_API_KEY&callback=showMap"
    async defer></script>
Lucky Soni
  • 6,811
  • 3
  • 38
  • 57
  • 1
    I have tried creating a variable that captures the response code. All it console.logs is undefined. Can you give me an example of how to capture the response code or how to use function gm_authFailure(). I have tried both and have had no success. – Aaron Jul 31 '17 at 00:10
  • It seems that the gm_authFaliure function does not receive any arguments hence you cannot check the type of error but you can be sure that something went wrong and handle it gracefully. See updated answer. – Lucky Soni Jul 31 '17 at 03:40
  • Could you show me how to integrate googleMapError with my code, I have tried several different ways and none of them work – Aaron Jul 31 '17 at 22:28
  • what are you trying to do when there is an error? Show a user message? – Lucky Soni Aug 01 '17 at 10:55
  • check updated answer. wait for about 10 seconds for the Google maps library to load after you click the `Run Code Snippet` button. – Lucky Soni Aug 01 '17 at 11:20
0

Yes, JavaScript supports try-catch blocks. Here is a sample implementation for your code:

(function (window, google, lat, lng) {
           var options = {
               center: {
                   lat: Number(lat),
                   lng: Number(lng)
               },
                 zoom: 5,
                 disableDefaultUI: true,
                 scrollwheel: true,
                 draggable: false
           },
           element = document.getElementById('map-canvas')
           try {
               var map = new google.maps.Map(element, options)
           } catch (error) {
               // handle error
               console.log(error.message);
           } finally {
               // optional cleanup code
           }
       }(window, window.google, result[i]['latitude'], result[i]['longitude']));
  • 1
    I already tried putting the try catch around var map = new google.maps.Map(element, options). It did not work – Aaron Jul 26 '17 at 23:06
  • 1
    Could you provide some more details about _how_ it didn't work, like a specific error message? – Simon Bilsky-Rollins Jul 26 '17 at 23:08
  • 1
    The try catch did not work. There was no specific error message. The try catch did not execute – Aaron Jul 26 '17 at 23:15
  • Ok, I think it's probably because the call to `google.maps.Map` is asynchronous and the entire block is executed before the call returns. Like [this other question](https://stackoverflow.com/questions/16316815/catch-statement-does-not-catch-thrown-error), you should move the try-catch block to a callback that is called after the Map object is created. Unfortunately, it doesn't look like the Google Maps API makes it very easy to do that. – Simon Bilsky-Rollins Jul 26 '17 at 23:32
0

As per google documentation.

If you exceed the usage limits you will get an OVER_QUERY_LIMIT status code as a response.

This means that the web service will stop providing normal responses and switch to returning only status code OVER_QUERY_LIMIT until more usage is allowed again. This can happen:

  • Within a few seconds, if the error was received because your application sent too many requests per second.

  • Within the next 24 hours, if the error was received because your application sent too many requests per day. The daily quotas are
    reset at midnight, Pacific Time.

Please refer this link. It would be helpful.

Community
  • 1
  • 1
Ravi Rupeliya
  • 621
  • 4
  • 16