我的代码在
下面所以我的问题是它工作正常但它应该跳过一个网址: http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1因为它不存在。
但是这样的网址存在http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2
如果我在没有循环的情况下测试我的应用程序,它会发出此错误,但仍会将其添加到db。下面是错误:
Request failed for http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=undefined returned
错误^所以我假设它跳过了它的cuz但我不希望它跳过那个错误只是那些不存在的错误。请帮忙。
var address = 'ip';
var user = 'user';
var userPwd = 'pw';
var db = 'db';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
function getJSON(id) {
var url = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=" + id;
var response = UrlFetchApp.fetch(url); // get api endpoint
var json = response.getContentText(); // get the response content as text
var data = JSON.parse(json)
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO items '
+ '(name, description, itemid, img) values (?, ?, ?, ?)');
stmt.setString(1,data.item.name);
stmt.setString(2, data.item.description);
stmt.setString(3,data.item.id);
stmt.setString(4, data.item.icon);
stmt.execute();
}
for(var i = 0; i < 50000; i++){
try{
Utilities.sleep(6000);
getJSON(i);
} catch(e) {
i++;
}
}
答案 0 :(得分:0)
将muteHttpExceptions参数与fetch()方法一起使用,以了解问题的确切位置。
变化:
var response = UrlFetchApp.fetch(url); // get api endpoint
要:
var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
Logger.log(response.getContentText());
检查日志是否有任何错误。
答案 1 :(得分:0)
进一步检查后,您可能希望获取URL的响应代码,然后添加用于保存到DB的脚本。
function myFunction() {
// Construct `fetch` params object
var params = {
'muteHttpExceptions' : true
};
// The code below logs the HTTP status code from the response received
// when fetching the Google home page.
// It should be 200 if the request succeeded.
var response = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1", params);
Logger.log(response.getResponseCode());
}
有关更多信息,请查看有关使用Google Apps脚本验证网址的教程和论坛:
从调试外部主机:
// Construct `fetch` params object
var params = {
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, params)
// Check return code embedded in response.
var rc = response.getResponseCode();
var responseText = response.getContentText();
if (rc !== 200) {
// Log HTTP Error
Logger.log("Response (%s) %s",
rc,
responseText );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
Logger.log( responseText );
}
如果没有,您可以尝试返回200然后插入数据库,忽略该URL。
希望这有帮助!