【发布时间】: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