How to catch UrlFetchApp.fetch exception
The trick is passing the muteHttpExceptions
param of UrlFetchApp.fetch()
.
Here an example (untested):
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))
// ...
}
For some reason if the URL is not available (e.g. the service you're trying to use is down) it still looks like is throwing an error so you may still need to use a try/catch
block.
Edit: This parameter is now documented here.
You can use the undocumented advanced option "muteHttpExceptions" to disable exceptions when a non-200 status code is returned, and then inspect the status code of the response. More information and an example is available on this issue.
why don't you use try catch and handle the error in catch block
try{
//Your original code, UrlFetch etc
}
catch(e){
// Logger.log(e);
//Handle error e here
// Parse e to get the response code
}