我正在学习有关如何使用Google Reseller API的教程。我已经来到了关于确定客户是否已存在于Google Apps(步骤2(的部分,但在处理Google_Service_Exception
对象时没有卡住。
如果客户不存在,则对 API 的调用将返回 404 错误。我正在使用 Google_Service_Exception
对象$e
的 code
属性来确定响应是否有 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
受到保护的事实有关。我想它受到保护是有原因的,所以我对改变类有点谨慎。解决此错误的任何帮助/指示将不胜感激。谢谢
只需使用 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_Exception
,Google_Exception
扩展Exception
。您可以在此处阅读有关异常的文档。您将看到getCode
方法。