Search code examples
google-apps-scripthttp-status-code-404

How can I handle exceptions from an external source, eg a 404?


So my goal is, using Google Appscripts, to call an external API for addresses, which returns a JSON/array with that information. 90% of the time, the API is fine. However, sometimes, I can legitimately call an address that is not in the API database, so the API gives me a 404 in this case.

My problem: When the API returns a 404, it ends the Appscript program that I am writing. How do I check the API response so that I can see if it is returning a 404 before I attempt to access it, which shuts the program down prematurely?

What I would like to do is to have the code: 1) understand an error has happened but still continue the program, 2) by creating an empty array in lieu of the property address data I am searching for. I know how to do 2), but I can't do 1 - I can't trigger the creation of that array based on the knowledge that a 404 call happened. Please help!

Thank you so much in advance!!

I have no idea what to try - I'm not sure I understand the handling exceptions portion of Appscript, because this is calling an external database and not an internal Google database, then returning a 404, so I don't know what applies and what does not.


Solution

  • Assuming that you call the API with UrlFetchApp, there are two ways to deal with it:

    1. Disable exceptions on unsuccessful requests by setting muteHttpExceptions:
      const options = {
        'method': 'get',
        'muteHttpExceptions': true
        // Include other necessary options like headers
      };
      
      const response = UrlFetchApp.fetch(apiUrl, options);
      const responseCode = response.getResponseCode();
      
      if (responseCode === 200) {
        // Success, process the data
      } else if (responseCode === 404) {
        // Handle 404 error
        console.log("API returned 404: Address not found");
      } else {
        // Handle other types of errors
        console.log("Error with response code: " + responseCode);
      }
      
    2. Wrap UrlFetchApp in try/catch block:
      try {
        const response = UrlFetchApp.fetch(apiUrl);
        const data = JSON.parse(response.getContentText());
      
        // Process your data
        // ...
      
      } catch (e) {
        // Check if the error is a 404
        if (e.message.includes("404")) {
          console.log("API returned 404: Address not found");
          // Handle 404 specific logic
        } else {
          // Handle other types of errors
          console.log("Error: " + e.message);
        }
      }