Home > Mobile >  Preventing GoogleJsonResponseException: API call to sheets.spreadsheets.batchUpdate failed with erro
Preventing GoogleJsonResponseException: API call to sheets.spreadsheets.batchUpdate failed with erro

Time:10-27

I have the following Google Spreadsheet function:

function deleteRows() {
  const sheetName = "Sheet"; // Please set the sheet name.
  
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(sheetName);
  const sheetId = sheet.getSheetId();
  const requests = sheet
    .getRange(`S1:S${sheet.getLastRow()}`)
    .createTextFinder("Found")
    .findAll()
    .map(r => r.getRow())
    .reverse()
    .map(r => ({deleteDimension:{range:{sheetId:sheetId,startIndex:r - 1,endIndex:r,dimension:"ROWS"}}}));
  Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}

The script deletes duplicated rows with API's batchUpdate, if there is text "Found" within column S, however sometimes there are no duplicated rows, hence I would like the function not to return the error:

GoogleJsonResponseException: API call to sheets.spreadsheets.batchUpdate failed with error: Must specify at least one request.

and just go on with the next function which runs after finishing the above deleteRows function.

How to prevent returning the error if there is no request?

CodePudding user response:

In your situation, how about the following modification?

From:

Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());

To:

if (requests.length > 0) {
  Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}
  • By this modification, when requests has the values, Sheets.Spreadsheets.batchUpdate is run.
  • Related