Search code examples
javascriptgoogle-apigoogle-calendar-apigoogle-api-js-client

Handle uncaught error for gapi.client.calendar.events.list


I just want to ask if there's way to catch error or to know that user can't get events from the calendar? What I want to do is add note that currently login email does not have authorization to access the events. Everything is working fine in which authorized email can access the events. Thank You for helping.

This is my code:

 gapi.client.calendar.events.list({
      'calendarId': calendarid,
      'timeMin': (new Date()).toISOString(),
      'showDeleted': false,
      'singleEvents': true,
      'maxResults': 10,
      'orderBy': 'startTime'
    }).then(function(response) { 
      var events = response.result.items;
      //appendPre('Upcoming events:');

      if (events.length > 0) {
        for (i = 0; i < events.length; i++) {
          var event = events[i];
          var when = event.start.dateTime;
          if (!when) {
            when = event.start.date;
          }
          //listingdata.push(event.summary+'('+when +'\n'+ event.description);

           //appendPre(event.summary + ' (' + when + ') ' + event.description)
        }
      } else {
         //appendPre('No upcoming events found.');
      }

    });

Solution

  • Every Google API must return a code 403 (Forbidden) when you're trying to access a resource you are not allowed to.

    So, you just have to catch the http response code :

     gapi.client.calendar.events.list({
          'calendarId': calendarid,
          'timeMin': (new Date()).toISOString(),
          'showDeleted': false,
          'singleEvents': true,
          'maxResults': 10,
          'orderBy': 'startTime'
        }).then(function(response) { 
          var events = response.result.items;
          //appendPre('Upcoming events:');
    
          if (events.length > 0) {
            for (i = 0; i < events.length; i++) {
              var event = events[i];
              var when = event.start.dateTime;
              if (!when) {
                when = event.start.date;
              }
              //listingdata.push(event.summary+'('+when +'\n'+ event.description);
    
               //appendPre(event.summary + ' (' + when + ') ' + event.description)
            }
          } else {
             //appendPre('No upcoming events found.');
          }
    
        }, function(error) {
              console.error("Execute error", error);
              if(error.code == 403)
              {
                console.log("No access")
              }
    
            });