【问题标题】:Issue with accessing property in Google_Service_Exception访问 Google_Service_Exception 中的属性的问题
【发布时间】:2016-07-19 09:28:52
【问题描述】:

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

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

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

我收到以下 PHP 错误:

致命错误:无法访问受保护的属性 Google_Service_Exception::$code。

Google_Service_Exception 类如下:

<?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 受到保护这一事实有关。我想它受到保护是有原因的,所以我对改变班级有点警惕。任何解决此错误的帮助/指针将不胜感激。谢谢

【问题讨论】:

    标签: php google-api google-apps google-api-php-client


    【解决方案1】:

    只需使用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 方法。

    【讨论】:

    • 太棒了,非常感谢。比我想象的要简单得多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多