【问题标题】:Catching error during api call not working?api调用期间捕获错误不起作用?
【发布时间】:2016-09-14 10:24:00
【问题描述】:

我正在尝试对 ip-​​api.com/json 进行 API 调用,但据我了解,它被广告拦截器阻止了。因此,我想添加一个 try-catch 以查看它何时失败,以便我可以用另一种方式解决这个问题,但脚本似乎没有进入 catch 块,而是抛出错误。

有没有办法捕捉这里抛出的异常?

$(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});
    }
});

catch 块永远不会被触发,而是抛出异常:

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

【问题讨论】:

  • try catch 为我执行..
  • @GuruprasadRao 我看到你在代码中添加了.error(function()..)。这会有所作为吗?即使我没有看到记录的响应,如果没有这部分,代码似乎也无法工作。
  • @GuruprasadRao 经过进一步调查,error() 实际上是抛出 ​​catch 语句捕获的异常的函数。

标签: javascript jquery json api exception-handling


【解决方案1】:

使用默认完成,无法触发错误。

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 );
        });

【讨论】:

  • 正是我想要的。谢谢!我认为jQuery docs 的链接也适合未来的读者。我在那里错过了它:/
猜你喜欢
  • 2017-01-18
  • 2021-10-06
  • 2019-03-02
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
相关资源
最近更新 更多