Best way to try / get HTTP response in Google Script

I'm still new to JavaScript and Google script apps, and this is the first time I try to use the Try / Catch statement.

I am running a script that connects to the page. It connects most of the time without issue, but sometimes it doesn't respond and throws an http error (or the response will be blank). I want to try / catch this answer so that I can run it 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 an exception , or always throws it.

Here's 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 200 HTTP response, it never throws a Page Connected error.

If someone can help me:

1) Is this the correct method to achieve what I want, or Try / Catch for something else? 2) Correct syntax.

I would be very grateful.

+3


source to share


2 answers


getResponseCode

does not throw an exception, but fetch

it does, so include it in a block try

:



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
  }
}

      

+4


source


As of today, you can muteHttpExceptions

parameter muteHttpExceptions

in options

UrlFetchApp.fetch(url, options)

. It disables HTTP exceptions.

This is not necessary try catch

- just check if the response code is ok.



+1


source







All Articles