thomaskessel
thomaskessel

Reputation: 447

Error Showing in Simple Google Apps Script, How to hide

I have a simple Google Apps Script that checks URLs, however, I would like to display something like "Not valid" for any non-200 status responses. Everything I try shows "#ERROR!" on the Google Sheet except for status 200 responses.

Here is my code:

function check_url(url) {
  var response = UrlFetchApp.fetch(url)
  if( response.getResponseCode() == 200 ) {
    return true
  } else if( response.getResponseCode() == 401 ) {
    return "401"
  } else {
    return "Not Valid"
  }  
}

Any help is greatly appreciated as I am not very familiar with GA scripts or Javascript.

Thanks!

Upvotes: 0

Views: 483

Answers (2)

TheMaster
TheMaster

Reputation: 50462

You should muteHTTPExceptions:

var response = UrlFetchApp.fetch(url,{'muteHTTPExceptions':true})

Also use arrays with fetchAll method, if you have a large number of urls to fetch.

Upvotes: 2

TheWizEd
TheWizEd

Reputation: 8606

This is a case where you need a try catch block. The fetch is throwing an error so there is no response.

function check_url(url) {
  try {
    var response = UrlFetchApp.fetch(url)
    if( response.getResponseCode() == 200 ) {
      return true
    } else if( response.getResponseCode() == 401 ) {
      return "401"
    }
  }
  catch(err) {
    return "Not Valid"
  }  
}

Upvotes: 1

Related Questions