有什麼方法可以從UrlFetchApp.fetch
中捕獲異常?如何捕獲UrlFetchApp.fetch異常
我想我可以用response.getResponseCode()
檢查響應代碼,但我不能,對於例如,當出現404錯誤,腳本不能繼續,只是停留在UrlFetchApp.fetch
有什麼方法可以從UrlFetchApp.fetch
中捕獲異常?如何捕獲UrlFetchApp.fetch異常
我想我可以用response.getResponseCode()
檢查響應代碼,但我不能,對於例如,當出現404錯誤,腳本不能繼續,只是停留在UrlFetchApp.fetch
編輯:此參數是現在documented here。
您可以使用未記錄的高級選項「muteHttpExceptions」在返回非200狀態代碼時禁用異常,然後檢查響應的狀態代碼。更多信息和示例請參閱this issue。
你爲什麼不使用嘗試捕捉和catch塊處理錯誤
try{
//Your original code, UrlFetch etc
}
catch(e){
// Logger.log(e);
//Handle error e here
// Parse e to get the response code
}
感謝您的快速響應。 當有異常時,是否可以找出響應代碼? – louis 2012-07-30 09:43:21
您將在e中得到一個錯誤字符串,您可以解析該錯誤字符串以獲取錯誤代碼。 – 2012-07-30 09:48:08
訣竅是通過muteHttpExceptions
參數UrlFetchApp.fetch()
。
下面一個例子(未經測試):
var payload = {"value": "key"}
var response = UrlFetchApp.fetch(
url,
{
method: "PUT",
contentType: "application/json",
payload: JSON.stringify(payload),
muteHttpExceptions: true,
}
);
var responseCode = response.getResponseCode()
var responseBody = response.getContentText()
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody)
// ...
} else {
Logger.log(Utilities.formatString("Request failed. Expected 200, got %d: %s", responseCode, responseBody))
// ...
}
出於某種原因,如果URL不可用(例如,你正在嘗試使用該服務已關閉),它仍然看起來就像是拋出一個錯誤,所以你可能仍然需要使用try/catch
塊。
謝謝,這是我想要的,谷歌應該有這個文件。 – louis 2012-08-06 09:16:15
謝謝,我總是忘記這個功能。 – oshliaer 2014-06-25 08:07:58