Friday, November 8, 2013

Google Calendar API V3 php error exception handing

Google's V3 api doesn't have a lot of documentation, which makes a number of things you might want to do with the API either difficult or error prone.  ( Actually, it has a TON of documentation, just not enough in the right places with a good enough search engine to help you find it ... )

If you can get past the OAUTH2 hurdle and implement some of the simple event list / fetch / update functions from the php examples documentation, you probably won't have any error handling.  The code will work as long as you don't have any errors, but when you include that code in your websites, eventually your users will see the friendly  red box error screen with a cryptic message, such as a POST error 404, instead of your web page.

The problem is that the Google API uses exceptions, but the examples don't include exception handling or any easy to find documentation that says 'a simple calendar operation has to include exception handling for a user friendly website'.

So, where you see an example like the following:
$event = $service->events->get('primary', 'eventId');

$event->setSummary('Appointment at Somewhere');

$updatedEvent = $service->events->update('primary', $event->getId(), $event);

You need to add exception handling on each of the Google API calls, or if you don't want to learn the API's and figure out what types of exception each call may throw, just put an error catcher around the whole block, something like so:
try {
   $event = $service->events->get('primary', 'eventId');

   $event->setSummary('Appointment at Somewhere');

   $updated = $service->events->update('primary', $event->getId(), $event);
} catch(Exception $e) {
     // Do something with the error here
}
The calendar API can throw several types of exception, named Google_ServiceException, Google_AuthException, Google_IOException, Google_CacheException. Exceptions are thrown for any errors, including passing a bad event ID, having problems with internet connections, or various other things that happen often enough to turn your wonderful website into a terrible user experience.


Now that you know how to avoid the red screen of death experience for your user's, you can take it from here to decide exactly what to do with any particular exception. Cheers!