在 Google_Service_Exception 中访问 属性 时出现问题

Issue with accessing property in Google_Service_Exception

我正在学习如何使用 Google Reseller API 的教程。我来到了确定客户是否已存在于 Google 应用程序(第 2 步)的部分,但在处理 Google_Service_Exception 对象时遇到了困难。

如果客户不存在,那么调用 API 将 return 出现 404 错误。我正在使用 Google_Service_Exception 对象 $ecode 属性 来确定响应是否有 404 错误。但是,当我尝试 return 使用 $e->code 的错误代码时:

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

我收到以下 PHP 错误:

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

Google_Service_Exceptionclass如下:

<?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;
  }
}

所以我假设错误与 $errors 受保护这一事实有关。我想它受到保护是有原因的,所以我对更改 class 有点谨慎。非常感谢解决此错误的任何帮助/指示。谢谢

只需使用getCode()方法:

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

Google_Service_Exception 扩展了 Google_ExceptionGoogle_Exception 扩展了 Exception。您可以在此处阅读 documentation about Exception。您将看到 getCode 方法。