I'm still new to JavaScript and Google apps script, and this is the first time I'm trying to use a 'Try/Catch' statement.
I'm running a script that connects to a page. It connects most of the time without issue, but occasionally it won't respond and throw a http error (Or, the response will be empty). I want to try/catch this response to have it run a second time if I get an error code, but I'm not 100% sure I understand the syntax, because no matter how I format it, It either never throws the exception, or always throws it.
Here is some sample code I've been experimenting with:
function myFunction() {
var response = UrlFetchApp.fetch("google.com");
Logger.log('Response Code: ' + response.getResponseCode());
try {if(response.getResponseCode() === 200);
} catch (err) {
throw 'Page connected';
}
}
If I can get this to work, I'm sure I can figure out the rest. However, even though the log shows me I get a HTTP response of 200, it never throws the error 'Page connected'.
If someone can guide me on:
1) Is this the correct method to achieve what I want, or is Try/Catch for something else? 2) The correct syntax.
I would be very grateful.
Handle POST Requests with Google Scripts The callback function doPost is invoked when an HTTP POST request is make to your Google Script URL that is published as a web app with anonymous access. const doPost = (request) => { console. log(request); return ContentService. crateTextOutput(JSON.
UrlFetchApp. Fetch resources and communicate with other hosts over the Internet. This service allows scripts to communicate with other applications or access other resources on the web by fetching URLs. A script can use the URL Fetch service to issue HTTP and HTTPS requests and receive responses.
UrlFetchApp methods are synchronous. They return an HttpResponse object, and they do not take a callback. That, apparently, is an API decision.
getResponseCode
does not throw an exception but fetch
does throw an exception, so include it inside your try
block:
function myFunction() {
try {
var response = UrlFetchApp.fetch("google.com");
Logger.log('Response Code: ' + response.getResponseCode());
if(response.getResponseCode() === 200) {
// something
}
} catch (err) {
// handle the error here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With