Error Handling Samples

The code samples below provide examples of common error handling functions using the AdWords API. Client Library.

Handle partial failures

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\ErrorHandling;

require '../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\Keyword;
use Google\AdsApi\AdWords\v201705\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example demonstrates how to handle partial failures when adding
 * keywords. To get ad groups run BasicOperations/GetAdGroups.php.
 */
class HandlePartialFailures {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    $keywords = [];

    $keyword = new Keyword();
    $keyword->setText('mars cruise');
    $keyword->setMatchType(KeywordMatchType::BROAD);
    $keywords[] = $keyword;

    $keyword = new Keyword();
    $keyword->setText('inv@lid cruise');
    $keyword->setMatchType(KeywordMatchType::BROAD);
    $keywords[] = $keyword;

    $keyword = new Keyword();
    $keyword->setText('venus cruise');
    $keyword->setMatchType(KeywordMatchType::BROAD);
    $keywords[] = $keyword;

    $keyword = new Keyword();
    $keyword->setText('b(a)d keyword cruise');
    $keyword->setMatchType(KeywordMatchType::BROAD);
    $keywords[] = $keyword;

    // Create ad group criteria and ad group criterion operations.
    $operations = [];
    foreach ($keywords as $keyword) {
      $adGroupCriterion = new BiddableAdGroupCriterion();
      $adGroupCriterion->setAdGroupId($adGroupId);
      $adGroupCriterion->setCriterion($keyword);

      $operation = new AdGroupCriterionOperation();
      $operation->setOperand($adGroupCriterion);
      $operation->setOperator(Operator::ADD);

      $operations[] = $operation;
    }

    // Create ad group criteria on the server.
    $result = $adGroupCriterionService->mutate($operations);

    // Print out some information about ad group criteria.
    foreach ($result->getValue() as $adGroupCriterion) {
      if ($adGroupCriterion->getCriterion() !== null) {
        printf(
            "Keyword with text '%s', match type '%s', and ID %d was added.\n",
            $adGroupCriterion->getCriterion()->getText(),
            $adGroupCriterion->getCriterion()->getMatchType(),
            $adGroupCriterion->getCriterion()->getId()
        );
      }
    }

    // Check for partial failures.
    if ($result->getPartialFailureErrors() !== null) {

      foreach ($result->getPartialFailureErrors() as $error) {
        // Get the index of the failed operation from the error's field path
        // elements.
        $fieldPathElements = $error->getFieldPathElements();
        $firstFieldPathElement = null;
        if ($fieldPathElements !== null && count($fieldPathElements) > 0) {
          $firstFieldPathElement = $fieldPathElements[0];
        }
        if ($firstFieldPathElement !== null
            && $firstFieldPathElement->getField() === 'operations'
            && $firstFieldPathElement->getIndex() !== null) {
          $index = $firstFieldPathElement->getIndex();
          $adGroupCriterion = $operations[$index]->getOperand();
          printf(
              "Keyword with text '%s' and match type '%s' failed with error "
                  . "'%s'.\n",
              $adGroupCriterion->getCriterion()->getText(),
              $adGroupCriterion->getCriterion()->getMatchType(),
              $error->getErrorString()
          );
        } else {
          printf("Operations failed with error '%s'.\n",
              $error->getErrorString());
        }
      }
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    // Partial failure behavior is also enabled in this example.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->enablePartialFailure()
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::AD_GROUP_ID));
  }
}

HandlePartialFailures::main();

Old

<?php
/**
 * This example demonstrates how to handle partial failures when adding
 * keywords. To get ad groups run BasicOperations/GetAdGroups.php.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once UTIL_PATH . '/ErrorUtils.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id to add keywords to
 */
function HandlePartialFailuresExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes. Passing true for the
  // parameter $partialFailure enables partial failure behavior.
  $adGroupCriterionService = $user->GetService('AdGroupCriterionService',
      ADWORDS_VERSION, null, null, null, true);

  // Create keywords.
  $keywords = array();
  $keywords[] = new Keyword('mars cruise', 'BROAD');
  $keywords[] = new Keyword('inv@lid cruise', 'BROAD');
  $keywords[] = new Keyword('venus cruise', 'BROAD');
  $keywords[] = new Keyword('b(a)d keyword cruise', 'BROAD');

  // Create ad group criteria and operations.
  $operations = array();
  foreach ($keywords as $keyword) {
    $adGroupCriterion = new BiddableAdGroupCriterion();
    $adGroupCriterion->adGroupId = $adGroupId;
    $adGroupCriterion->criterion = $keyword;

    $operation = new AdGroupCriterionOperation();
    $operation->operand = $adGroupCriterion;
    $operation->operator = 'ADD';

    $operations[] = $operation;
  }

  // Make the mutate request.
  $result = $adGroupCriterionService->mutate($operations);

  // Display results.
  foreach ($result->value as $adGroupCriterion) {
    if ($adGroupCriterion->AdGroupCriterionType == 'BiddableAdGroupCriterion') {
      printf("Keyword with text '%s', match type '%s', and ID '%s' was "
          . "added.\n", $adGroupCriterion->criterion->text,
          $adGroupCriterion->criterion->matchType,
          $adGroupCriterion->criterion->id);
    }
  }

  // Check for partial failures.
  if (isset($result->partialFailureErrors)) {
    foreach ($result->partialFailureErrors as $error) {
      $index = ErrorUtils::GetSourceOperationIndex($error);
      if (isset($index)) {
        $adGroupCriterion = $operations[$index]->operand;
        printf("Keyword with text '%s' and match type '%s' failed with error "
            . "'%s'.\n", $adGroupCriterion->criterion->text,
          $adGroupCriterion->criterion->matchType, $error->errorString);
      } else {
        printf("Operations failed with error '%s'.\n", $error->errorString);
      }
    }
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  HandlePartialFailuresExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Handle policy violation errors

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\ErrorHandling;

require '../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\ApiException;
use Google\AdsApi\AdWords\v201705\cm\ExemptionRequest;
use Google\AdsApi\AdWords\v201705\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\PolicyViolationError;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example demonstrates how to handle policy violation errors when creating
 * text ads.
 */
class HandlePolicyViolationError {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $session->setValidateOnly(true);
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);

    // Create text ad that violates an exemptable policy.
    $expandedTextAd = new ExpandedTextAd();
    $expandedTextAd->setHeadlinePart1('Mars Cruise !!!');
    $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.');
    $expandedTextAd->setDescription('Low-gravity fun for everyone!');
    $expandedTextAd->setFinalUrls(['http://www.example.com']);

    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($expandedTextAd);

    // Create ad group ad operation and add it to the list.
    $operations = [];
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    try {
      // Try creating an ad group ad on the server.
      $result = $adGroupAdService->mutate($operations);
    } catch (ApiException $apiException) {
      $operationIndicesToRemove = [];
      foreach ($apiException->getErrors() as $error) {
        // Get the index of the failed operation from the error's field path
        // elements.
        $fieldPathElements = $error->getFieldPathElements();
        $firstFieldPathElement = null;
        if ($fieldPathElements !== null && count($fieldPathElements) > 0) {
          $firstFieldPathElement = $fieldPathElements[0];
        }
        if ($firstFieldPathElement === null
            || $firstFieldPathElement->getField() !== 'operations'
            || $firstFieldPathElement->getIndex() === null) {
          // If the operation index is not present on the first error field
          // path element, then there's no way to determine which operation to
          // remove, so simply throw the exception.
          throw $apiException;
        }
        $operationIndex = $firstFieldPathElement->getIndex();
        $operation = $operations[$operationIndex];
        if ($error instanceof PolicyViolationError) {
          printf("Ad with headline part 1 '%s' violated %s policy '%s'.\n",
              $operation->getOperand()->getAd()->getHeadlinePart1(),
              $error->getIsExemptable() ? 'exemptable' : 'non-exemptable',
              $error->getExternalPolicyName()
          );
          if ($error->getIsExemptable() === true) {
            // Add exemption request to the operation.
            printf(
                "Adding exemption request for policy name '%s' on text "
                    ."'%s'.\n",
                $error->getKey()->getPolicyName(),
                $error->getKey()->getViolatingText()
            );
            $operation->setExemptionRequests(
                [new ExemptionRequest($error->getKey())]);
          } else {
            // Remove non-exemptable operation.
          print "Removing non-exemptable operation from the request.\n";
            $operationIndicesToRemove[] = $operationIndex;
          }
        } else {
          // Non-policy error returned.
          printf(
              "Ad with headline part 1 '%s' created non-policy error '%s'.\n",
              $operation->getOperand()->getAd()->getHeadlinePart1(),
              $error->getErrorString()
          );
          print "Removing the operation causing non-policy error from the "
              . "request.\n";
          $operationIndicesToRemove[] = $operationIndex;
        }
      }
      $operationIndicesToRemove = array_unique($operationIndicesToRemove);
      rsort($operationIndicesToRemove, SORT_NUMERIC);
      foreach ($operationIndicesToRemove as $operationIndex) {
        unset($operations[$operationIndex]);
      }
    }

    if (count($operations) > 0) {
      // Make the mutate request to really add an ad group ad.
      $session->setValidateOnly(false);
      $result = $adGroupAdService->mutate($operations);

      // Print out some information about the created ad group ad.
      foreach ($result->getValue() as $adGroupAd) {
        printf(
            "Expanded text ad with headline part 1 '%s' and ID '%s' was added."
                . "\n",
            $adGroupAd->getAd()->getHeadlinePart1(),
            $adGroupAd->getAd()->getId()
        );
      }
    } else {
      print "All the operations were invalid with non-exemptable errors.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    // Partial failure behavior is also enabled in this example.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::AD_GROUP_ID));
  }
}

HandlePolicyViolationError::main();

Old

<?php
/**
 * This example demonstrates how to handle policy violation errors when creating
 * text ads.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

require_once UTIL_PATH . '/ErrorUtils.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the if the ad group to add the text ads to
 */
function HandlePolicyViolationErrorExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Get validateOnly version of the AdGroupAdService.
  $adGroupAdValidationService =
      $user->GetService('AdGroupAdService', ADWORDS_VERSION, null, null, true);

  // Create text ad that violates an exemptable policy. This ad will only
  // trigger an error in the production environment.
  $textAd = new TextAd();
  $textAd->headline = 'Mars Cruise !!!';
  $textAd->description1 = 'Visit the Red Planet in style.';
  $textAd->description2 = 'Low-gravity fun for everyone!';
  $textAd->displayUrl = 'www.example.com';
  $textAd->finalUrls = array('http://www.example.com/');

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $textAd;

  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;
  $operation->operator = 'ADD';

  $operations = array($operation);

  try {
    // Make the mutate request.
    $result = $adGroupAdValidationService->mutate($operations);
  } catch (SoapFault $fault) {
    $errors = ErrorUtils::GetApiErrors($fault);
    if (sizeof($errors) == 0) {
      // Not an API error, so throw fault.
      throw $fault;
    }
    $operationIndicesToRemove = array();
    foreach ($errors as $error) {
      if ($error->ApiErrorType == 'PolicyViolationError') {
        $operationIndex = ErrorUtils::GetSourceOperationIndex($error);
        $operation = $operations[$operationIndex];
        printf("Ad with headline '%s' violated %s policy '%s'.\n",
            $operation->operand->ad->headline,
            $error->isExemptable ? 'exemptable' : 'non-exemptable',
            $error->externalPolicyName);
        if ($error->isExemptable) {
          // Add exemption request to the operation.
          printf("Adding exemption request for policy name '%s' on text "
              ."'%s'.\n", $error->key->policyName, $error->key->violatingText);
          $operation->exemptionRequests[] = new ExemptionRequest($error->key);
        } else {
          // Remove non-exemptable operation.
          print "Removing the operation from the request.\n";
          $operationIndicesToRemove[] = $operationIndex;
        }
      } else {
        // Non-policy error returned, throw fault.
        throw $fault;
      }
    }
    $operationIndicesToRemove = array_unique($operationIndicesToRemove);
    rsort($operationIndicesToRemove, SORT_NUMERIC);
    foreach ($operationIndicesToRemove as $operationIndex) {
      unset($operations[$operationIndex]);
    }
  }

  if (sizeof($operations) > 0) {
    // Retry the mutate request.
    $result = $adGroupAdService->mutate($operations);

    // Display results.
    foreach ($result->value as $adGroupAd) {
      printf("Text ad with headline '%s' and ID '%s' was added.\n",
          $adGroupAd->ad->headline, $adGroupAd->ad->id);
    }
  } else {
    print "All the operations were invalid with non-exemptable errors.\n";
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  HandlePolicyViolationErrorExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.