2016-09-24 53 views
0

我的代碼如下谷歌腳本:應用程序跳過有效網址

所以我的問題是,它工作正常,但它應該跳過一個網址,如: http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1,因爲它不存在。

但如果我測試我的應用程序,而不循環它將給這個錯誤,但仍然把它添加到數據庫這樣的URL存在http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2

。繼承人的錯誤:

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

對fetch()方法使用muteHttpExceptions參數來知道問題出在哪裏。

變化:

var response = UrlFetchApp.fetch(url); // get api endpoint 

要:

var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true}); 
Logger.log(response.getContentText()); 

檢查日誌中是否存在錯誤。

+0

同樣的事情仍然會跳過大量有效的網址。 –

+0

您在跳過的URL的日誌中得到了什麼? –

0

進一步檢查後,您可能想要獲取url的響應代碼,然後添加腳本以保存到數據庫。

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

欲瞭解更多信息,請查看關於使用谷歌Apps腳本URL驗證的教程和論壇:

從調試外部主機:

// 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。

希望這會有所幫助!

相關問題