Search code examples
phpgoogle-apigoogle-appsgoogle-api-php-client

Issue with accessing property in Google_Service_Exception


I'm following a tutorial on how to use the Google Reseller API. I've come to the section on determining whether a customer already exists in Google Apps (Step 2) but have come unstuck in handling the Google_Service_Exception object.

If a customer doesn't exist then a call to the API will return a 404 error. I'm using the code property of the Google_Service_Exception object $e to determine if the response has a 404 error. However when I try to return the error code with $e->code with:

try {
 // Call to the Google Reseller API
} catch (Google_Service_Exception $e) {
  if($e->code == 404){
    return false;
  }
}

I get the following PHP error:

Fatal error: Cannot access protected property Google_Service_Exception::$code.

The Google_Service_Exception class is as follows:

<?php

require_once 'Google/Exception.php';

class Google_Service_Exception extends Google_Exception
{
  /**
   * Optional list of errors returned in a JSON body of an HTTP error response.
   */
  protected $errors = array();

  /**
   * Override default constructor to add ability to set $errors.
   *
   * @param string $message
   * @param int $code
   * @param Exception|null $previous
   * @param [{string, string}] errors List of errors returned in an HTTP
   * response.  Defaults to [].
   */
  public function __construct(
      $message,
      $code = 0,
      Exception $previous = null,
      $errors = array()
  ) {
    if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
      parent::__construct($message, $code, $previous);
    } else {
      parent::__construct($message, $code);
    }

    $this->errors = $errors;
  }

  /**
   * An example of the possible errors returned.
   *
   * {
   *   "domain": "global",
   *   "reason": "authError",
   *   "message": "Invalid Credentials",
   *   "locationType": "header",
   *   "location": "Authorization",
   * }
   *
   * @return [{string, string}] List of errors return in an HTTP response or [].
   */
  public function getErrors()
  {
    return $this->errors;
  }
}

So I assumed the error has something to do with the fact that $errors is protected. I imagine it is protected for a reason so I was a bit wary of changing the class. Any help / pointers in working around this error would be greatly appreciated. Thanks


Solution

  • Just use the getCode() method:

    try {
         // Call to the Google Reseller API
    } catch (Google_Service_Exception $e) {
         if($e->getCode() == 404){ // <- Change is here
             return false;
         }
    }
    

    Google_Service_Exception extends Google_Exception and Google_Exception extends Exception. You may read the documentation about Exception here. You will see the getCode method.