Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective

I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet.

Issue:

When I debug the script, everything runs smoothly without any major problems. However, when I try running it directly from the menu button in the Spreadsheet, certain steps of the script execute before encountering a Service Error: Spreadsheet with no specifics provided.

Anomaly

To monitor the progress of the process while running outside of the debugger, I began logging each step to a cell in the Spreadsheet.

The strange part is, whenever I try moving pieces of code randomly like :

sheet.getRange("F2").setValue(currentPage);

the code breaks at different points.

Code Snippet :

You can access the code to replicate the issue here: http://pastebin.com/HjmSwEYZ

Simply follow these steps:

1 - Create a new spreadsheet on Google Drive

2 - Go to Tools -> Script Editor

3 - Insert a new script, paste the code, and save it

4 - Refresh the spreadsheet (F5) to display the custom menu "Guild Wars 2 Tracker"

5 - Click the button and select "List All"

Expected Outcome:

If not for this error, the code would ideally:

1 - Send a request to this URL: (fetching the first page of Guild Wars 2 items)

2 - Iterate through each page, parse the json data, and write the extracted values into the spreadsheet

Note:

Please excuse the abundance of "Log" messages in the sheet. This was my attempt to track progress; I am aware it's not best practice.

Thank you in advance

Update 1:

After replicating the code from pastebin in a new spreadsheet as its own script project, I managed to run it once successfully. However, it then encountered a separate error stating:

We're sorry, a server error occurred. Please wait a bit and try again.

Answer №1

If you encounter service errors like this, it might be due to accessing incorrect ranges, and the error may only show up during a subsequent access. For instance, if you attempt to reference columns or rows that do not exist in your spreadsheet, such as referencing column H when you only have columns A-E, or trying to access row 10001 when you actually have only 10000 rows.

The Apps Script Issue Tracker has information on this matter: https://issuetracker.google.com/issues/68062620

Regarding the root cause of your problem, it seems that your script is not optimized and does not adhere to the best practices recommended by Google for using the Spreadsheet Service. It's advisable to utilize batch operations like the Range#setValues method to write entire blocks of data, or at least use appendRow to add rows one by one (instead of individual cell updates with

sheet.getRange(rowIndex, someColumn).setValue(oneValue)
). These methods automatically adjust the sheet to accommodate new data entries.

Here's an example modification suggested for your code:

var itemFields = [ "name",
                   "rarity",
                   "price_last_changed",
                   "max_offer_unit_price",
                   "min_sale_unit_price",
                   "offer_availability",
                   "sale_availability" ];
function addResultPage_(sheet, results) {
  const imgs = [],
  const data = results.map(function (result, index) {
    if (result.img)
      imgs.push({row: index, url: result.img});
    return itemFields.map(function (field) { return result[field] || ""; });
  });
  if (!data.length) return;

  const startRow = sheet.getLastRow() + 1;
  sheet.getRange(startRow, 2, data.length, data[0].length).setValues(data);
  if (imgs.length)
    imgs.forEach(function (imgInfo) {
      sheet.insertImage(imgInfo.url, 1, startRow + imgInfo.row);
    });
}
function listAllItems() {
  const sheet = SpreadsheetApp.getActiveSheet(),
        totalPages = updateStartStatus("List All Items");

  for (var page = 1; page <= totalPages; ++page) {
    var pageResults = getItemsByPage(page);
    if (pageResults.results)
      addResultPage_(sheet, pageResults.results);
    else
      console.warn({message: "No results for page '" + page + "'", resp: pageResults});
  }
}

Answer №2

I found ellockie's response helpful as I encountered a similar issue without realizing it. Initially, I attempted to sort a range using range.sort(8), but for collecting the range, I mistakenly used:

sheet.getRange(2, 1, sheet.getMaxRows(), sheet.getMaxColumns());

In hindsight, the correct approach would have been:

sheet.getRange(2, 1, sheet.getMaxRows() - 1, sheet.getMaxColumns());

As of the latest update on 5/1/2015, the error message remains vague and uninformative, displaying only "Service error: Spreadsheets".

Answer №3

Hey there Marchello, I faced a similar issue today and managed to find a solution by following this link: https://example.com/solution-code (check out #4). The workaround involves adding rows at the end of the spreadsheet to kickstart the script functionality once more. This approach successfully resolved my problem.

Answer №4

Experiencing a similar issue but managed to uncover the root problem, which turned out to be attempting to duplicate just one cell... CAN YOU IMAGINE?

A segment of the code was aimed at erasing a single row, and that stubborn cell persisted. After trying to replicate a single row and causing the entire Spreadsheet to crash, I rebooted and proceeded to copy cells individually only to realize that an empty cell triggered the crash. Removing the whole column along with other vacant columns led me through the gates of success!

Now, copying an entire row works flawlessly with the script!!!!!

Answer №5

My experience involved using formulas with 'dynamic' ranges like =sum(b2:b), which I recall was highlighted as a potential issue in the updated google spreadsheets.

By adjusting to sum(b2:b22) (ensuring the range stays within the sheet's final row), I was able to resolve the issue successfully.

Answer №6

The reason for the error in my scenario was due to me instructing a different spreadsheet to organize its data based on 25 columns, even though it only had 19 columns available.

In hindsight, I realized that I had made the mistake of deleting unnecessary columns from the spreadsheet after already writing the script to sort 25 columns instead of utilizing getLastColumn method - an error that could have been easily avoided.

Answer №7

One issue I encountered was the same as what ellockie pointed out: The need for dynamic range in a formula. In my situation, I previously used =INDEX(B7:B,1) to retrieve the first cell following my column header - B7. This approach was necessary because I had a script that would insert a new cell and move all existing data down. As a result, I needed a way to consistently reference the first row value regardless of cell movement. I eventually switched to using

=INDIRECT(CONCATENATE(CHARACTER(COLUMN()+64);ROW()+4))
in order to make the reference dynamic.

  • CHARACTER(COLUMN()+64) provides the column letter, essentially replacing =INDEX(B7:B,1) with B
  • ROW()+4 gives me the desired row number, which is 4 rows beneath where this formula resides. This replaces =INDEX(B7:B,1) with 7

Answer №8

I encountered a similar issue where an error started appearing during the script execution.

The error specifically mentioned that the Service Spreadsheets failed while trying to access a document with an ID.

Upon investigation, I realized that the problem stemmed from formulas referencing ranges that had been shifted.

To resolve this issue, I adjusted the affected formulas by including headers or an extra cell to ensure they remained accurate when new cells were added.

For example, in one instance, I was inserting new cells above row 5 through a script, causing my SUMIFS formulas on other sheets to sum data from row 5.

My solutions included:

  1. Adding an extra cell to formulas to prevent them from being affected by new cell additions

In another scenario, I modified the SUMIFS formula to start summing from row 4 (headers) instead of row 5. This approach had worked well in the past.

During development, I inadvertently altered these formulas to reference row 4 instead of row 5, leading to the script failure in Google Sheets.

  1. If the first method doesn't work, consider using the INDIRECT function instead of direct range references. This allowed me to continue using SUMIFS from row 5 without any issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

The console is reporting an error stating it cannot read the charCodeAt property

<script> var str=prompt('please enter a string'); var a= str.split(''); for (j=0; j<str.length; j++){ for(i=j; i<str.length; i++) { if(a[i].charCodeAt(0) > a[i+1].charCodeAt(0)) { var b= a[i]; a[i]=a[i+ ...

Executing a PHP script to initiate a ping transmission

I have a project to complete for my university involving the development of a simple application. However, I lack experience in this area and am unsure how to proceed. The objective is straightforward: I want to send ping requests to 50 IP addresses at t ...

Firefox browser does not display flashing titles for tabs

Every second, I want to display "New message..." in the title when the browser tab is inactive or the user is in another tab. Here's the code I used: <script> var mytimer; function log() { document.title = document.title == "" ...

Managing Server Crashes in Node.js

Is there a way to automatically update the database whenever my node.js server crashes or stops? Similar to how try{}catch(){}finally(){} works in JAVA. I am new to this. Does Node emit any events before shutting down so that I can run my function then? ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

Steps to create a personalized material-ui element

I am looking to create a custom time duration component by modifying the TextField component. https://i.stack.imgur.com/fLsFs.png https://i.stack.imgur.com/SdpdH.png If anyone has any advice or assistance, it would be greatly appreciated. Thank you! ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

How can you show a different value in a select menu with AngularJS on selection?

When designing my menu to display US States for selection, I wanted to show both the 2-letter state code and the full name of the state initially. However, once the user selects a state, I only want to display the 2-letter code. This is how my menu looks: ...

Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename. Can someone assist me with this? Here is a Js fiddle that I've been working on. This is my HTML mark ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Transform the results of a database query into JSON format using Node.js

Below is the code snippet I have written: oracledb.getConnection( { user : "user", password : "password", connectString : "gtmachine:1521/sde1" }, function(err, connection) { if (err) { console.error(err); return; } ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Using values from a designated line within the textarea to successfully submit a GET form

How can I extract values from a specific line in a TextArea and use them to submit a form? <!DOCTYPE html> <html> <body> <input type='button' value='submit' onclick='document.getElementById("submit-line-3") . ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...