Search code examples
javascriptgoogle-apps-scripttry-catch

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.


Solution

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