Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to Try/Catch HTTP response in Google Script

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.

like image 606
HDCerberus Avatar asked Oct 10 '14 12:10

HDCerberus


People also ask

How do I handle GET and POST HTTP requests in Google Apps Script?

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.

What is UrlFetchApp?

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.

Is UrlFetchApp synchronous?

UrlFetchApp methods are synchronous. They return an HttpResponse object, and they do not take a callback. That, apparently, is an API decision.


1 Answers

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
  }
}
like image 63
Nick Russler Avatar answered Sep 23 '22 22:09

Nick Russler