UrlFetchApp.fetch() gives SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON about 1/5 of the time Google script

230 views Asked by At

I have been using UrlFetchApp.fetch() for years with no issues

But recently, I randomly get this error message about once every five times I refreshed.

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

I have spent hours researching how to fix this but found nothing that works.

Any insight is appreciated.

function fetch() {
  var source = UrlFetchApp.fetch("https://sum-app.net/projects/151546202312131392/download_data/kumu_json").getContentText();
  var data = JSON.parse(source);
  return data;
}
1

There are 1 answers

1
TheMaster On BEST ANSWER

It means your server is sending Html and not json. This might happen due to various reasons, like rate limiting(in which case, you can try exponential backoff algorithm) or internal server errors.

function fetch() {
  const res = UrlFetchApp.fetch("https://sum-app.net/projects/151546202312131392/download_data/kumu_json"),
    source = res.getContentText(),
    code = res.getResponseCode();
  if(code === 200){
     const data = JSON.parse(source);
     return data;
  } else {
     console.error({code})
     console.error(res.getContentText())
     throw new Error("Oops! Something went wrong!")
  }
}