【问题标题】:Try Catch for error message in google maps api尝试在谷歌地图 api 中捕获错误消息
【发布时间】:2018-01-02 10:57:36
【问题描述】:

我正在使用 javascript 并收到一条消息,表明我已超出此 API 的每日请求配额。有没有办法在 try catch 块中捕获此错误消息,这样当我超过配额时,我可以执行另一段代码。我看过几个类似的帖子,但没有任何帮助。这是我的代码。

(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']));

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    更新 根据documentation

    如果您想以编程方式检测身份验证失败(例如自动发送信标),您可以准备一个回调函数。如果定义了以下全局函数,它将在身份验证失败时调用。 function gm_authFailure() {//代码}

    这是一个list gm_authFaliure 函数应该能够捕获的错误。它还提到了 OverQuotaMapError 错误。

    根据documentation

    如果在特定时间段内发出过多请求,API 会返回 OVER_QUERY_LIMIT 响应代码。

    所以你应该检查响应代码。如果 Google maps javascript 库不允许访问响应代码,那么我建议向 API 发出 HTTP 请求以获取响应代码。

    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>

    【讨论】:

    • 我尝试创建一个捕获响应代码的变量。所有它 console.logs 都是未定义的。你能给我一个如何捕获响应代码或如何使用函数 gm_authFailure() 的示例。我都试过了,都没有成功。
    • gm_authFaliure 函数似乎没有接收任何参数,因此您无法检查错误的类型,但您可以确定出现问题并优雅地处理它。查看更新的答案。
    • 您能告诉我如何将 googleMapError 与我的代码集成吗,我尝试了几种不同的方法,但都没有奏效
    • 出现错误时你想做什么?显示用户消息?
    • 检查更新的答案。单击Run Code Snippet 按钮后,等待大约 10 秒以加载 Google 地图库。
    【解决方案2】:

    是的,JavaScript supports try-catch blocks。这是您的代码的示例实现:

    (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']));
    

    【讨论】:

    • 我已经尝试将 try catch 放在 var map = new google.maps.Map(element, options) 周围。它没有工作
    • 您能否提供更多关于它如何不起作用的详细信息,例如特定的错误消息?
    • try catch 不起作用。没有具体的错误信息。 try catch 没有执行
    • 好吧,我想这可能是因为对google.maps.Map的调用是异步的,整个块在调用返回之前执行。与this other question 一样,您应该将 try-catch 块移动到在 Map 对象创建后调用的回调中。不幸的是,Google Maps API 看起来并不容易做到这一点。
    【解决方案3】:

    根据谷歌文档。

    如果您超出使用限制,您将获得 OVER_QUERY_LIMIT 状态 代码作为响应。

    这意味着网络服务将停止提供正常响应 并切换到仅返回状态码 OVER_QUERY_LIMIT 直到更多 再次允许使用。这可能发生:

    • 如果由于您的应用每秒发送的请求过多而收到错误,则在几秒钟内。

    • 在接下来的 24 小时内,如果收到错误是因为您的应用程序每天发送的请求过多。每日配额是
      在太平洋时间午夜重置。

    请参考this链接。这会很有帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多