如何忽略Google People API删除不存在联系人时的错误?
批量删除Google联系人时忽略404错误的解决方案
问题场景
本地系统与Google Contact同步,批量删除联系人时,若列表中存在已被用户删除的联系人(返回404错误),Cron任务会因Google\Service\Exception致命错误终止,无法继续删除剩余有效联系人。
原代码问题
原代码中调用people->get()检查联系人存在性时,若联系人不存在会直接抛出致命错误,而非返回空值,导致循环中断:
$a_deleteContact = array("people/1XXXXXXXXXXX","people/2XXXXXXXXXXX","people/3XXXXXXXXXXX","people/4XXXXXXXXXXX"); foreach($a_deleteContact as $contactResourceName) { $client = new Google_Client(); $accessToken = json_decode(file_get_contents($this->tokenPath), true); $client->setAccessToken($accessToken); $service = new Google_Service_PeopleService($client); $profile = $service->people->get($contactResourceName,array('personFields' => 'metadata')); $etag = $profile->etag; if(!empty($etag)) { $service->people->deleteContact($contactResourceName); } }
收到的错误信息:
Fatal error: Uncaught Google\Service\Exception: { "error": { "code": 404, "message": "Requested entity was not found.", "errors": [ { "message": "Requested entity was not found.", "domain": "global", "reason": "notFound" } ], "status": "NOT_FOUND" } } in /public_html/vendor/google/apiclient/src/Http/REST.php:128 Stack trace: #0 /public_html/vendor/google/apiclient/src/Http/REST.php(103): Google\Http\REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google\\Service\\...') #1 [internal function]: Google\Http\REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google\\Service\\...') #2 /public_html/vendor/google/apiclient/src/Task/Runner.php(182): call_user_func_array(Array, Array) #3 /public_html/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run() #4 /public_html/vendor/google/apiclient/src/Client.php(898): in /public_html/vendor/google/apiclient/src/Http/REST.php on line 128
解决方案:捕获异常并跳过错误项
通过try-catch块捕获Google\Service\Exception,判断错误码是否为404,若是则跳过当前联系人,继续执行循环。同时优化代码,将客户端和服务实例初始化移到循环外,避免重复创建对象:
$a_deleteContact = array("people/1XXXXXXXXXXX","people/2XXXXXXXXXXX","people/3XXXXXXXXXXX","people/4XXXXXXXXXXX"); // 初始化客户端和服务,移到循环外提升性能 $client = new Google_Client(); $accessToken = json_decode(file_get_contents($this->tokenPath), true); $client->setAccessToken($accessToken); $service = new Google_Service_PeopleService($client); foreach($a_deleteContact as $contactResourceName) { try { // 尝试获取联系人信息,捕获404错误 $profile = $service->people->get($contactResourceName, array('personFields' => 'metadata')); if(!empty($profile->etag)) { $service->people->deleteContact($contactResourceName); } } catch (Google\Service\Exception $e) { // 仅忽略404未找到错误,其他异常仍抛出 if ($e->getCode() !== 404) { throw $e; } // 可选:记录日志,方便排查 // error_log("联系人 {$contactResourceName} 不存在,跳过删除: " . $e->getMessage()); } }
关键说明
- 异常捕获:针对
Google\Service\Exception进行捕获,判断错误码是否为404,仅跳过该类错误,其他异常(如权限错误、API配额耗尽)仍会抛出,避免隐藏其他问题。 - 性能优化:将
Google_Client和Google_Service_PeopleService的初始化移到循环外部,避免每次循环重复创建对象,提升执行效率。 - 可选日志:可添加日志记录跳过的联系人,便于后续同步排查。
内容的提问来源于stack exchange,提问作者Rishi Pal
相关产品推荐
相关产品推荐

