甚至在发生致命错误后继续:未捕获的异常

时间:2015-02-01 11:54:10

标签: php error-handling google-api

我正在查询谷歌API,其荒谬的下限为100 /天,我得到:

Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET ...

..并且脚本在此之后无法执行任何操作。

如何防止它失败并至少保存到目前为止收到的任何数据?我将数据保存在数组中:

function searchImages($service, $optParams, $query) {
  $results = $service->cse->listCse($query, $optParams);
  return $results;
}
$descriptionSearch = searchImages($customsearchService, $customsearchService_optParams, $descriptions[$i]);
foreach ($descriptionSearch->items as $item) {
  array_push($list[$item_codes[$i]], strtok($item->link,'?'));
}

1 个答案:

答案 0 :(得分:1)

function searchImages($service, $optParams, $query) {
  try {
      $results = $service->cse->listCse($query, $optParams);
  }catch (Exception $e) {
      // should log this exception... you can use Log4PHP
      return NULL;
  }
  return $results;
}

$descriptionSearch = searchImages($customsearchService,customsearchService_optParams, $descriptions[$i]);
if (!is_null($descriptionSearch)) {
    foreach ($descriptionSearch->items as $item) {
        array_push($list[$item_codes[$i]], strtok($item->link,'?'));
    }
}