Google Ads API is returning to beta status. Please read our blog post for more details.

Handle Partial Failure

Java
// Copyright 2019 Google LLC
//
// 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
//
//     https://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 com.google.ads.googleads.examples.errorhandling;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v2.errors.GoogleAdsError;
import com.google.ads.googleads.v2.errors.GoogleAdsException;
import com.google.ads.googleads.v2.resources.AdGroup;
import com.google.ads.googleads.v2.services.AdGroupOperation;
import com.google.ads.googleads.v2.services.AdGroupServiceClient;
import com.google.ads.googleads.v2.services.MutateAdGroupResult;
import com.google.ads.googleads.v2.services.MutateAdGroupsResponse;
import com.google.ads.googleads.v2.utils.ErrorUtils;
import com.google.ads.googleads.v2.utils.ResourceNames;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

/**
 * Shows how to handle partial failures. There are several ways of detecting partial failures. This
 * highlights the top main detection options: empty results and error instances.
 *
 * <p>Access to the detailed error (<code>GoogleAdsFailure</code>) for each error is via a Any
 * proto. Deserializing these to retrieve the error details is may not be immediately obvious at
 * first, this example shows how to convert Any into <code>GoogleAdsFailure</code>.
 *
 * <p>Additionally, this example shows how to produce an error message for a specific failed
 * operation by looking up the failure details in the <code>GoogleAdsFailure</code> object.
 */
public class HandlePartialFailure {

  private static class HandlePartialFailureParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;
  }

  public static void main(String[] args) throws InvalidProtocolBufferException {
    HandlePartialFailureParams params = new HandlePartialFailureParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID");
      params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID");
    }
    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new HandlePartialFailure().runExample(googleAdsClient, params.customerId, params.campaignId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
    }
  }

  /** Runs the example. */
  public void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId)
      throws InvalidProtocolBufferException {
    MutateAdGroupsResponse response = createAdGroups(googleAdsClient, customerId, campaignId);

    // Checks for existence of any partial failures in the response.
    if (checkIfPartialFailureErrorExists(response)) {
      System.out.println("Partial failures occurred.");
    } else {
      System.out.println("All operations completed successfully. No partial failures to show.");
      return;
    }

    // Finds the failed operations by looping through the results.
    printResults(response);
  }

  /**
   * Attempts to create 3 ad groups with partial failure enabled. One of the ad groups will succeed,
   * while the other will fail.
   */
  private MutateAdGroupsResponse createAdGroups(
      GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
    // This AdGroup should be created successfully - assuming the campaign in the params exists.
    AdGroup group1 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
            .setName(StringValue.of("Valid AdGroup: " + System.currentTimeMillis()))
            .build();
    // This AdGroup will always fail - campaign ID 0 in resource names is never valid.
    AdGroup group2 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, 0L)))
            .setName(StringValue.of("Broken AdGroup: " + System.currentTimeMillis()))
            .build();
    // This AdGroup will always fail - duplicate ad group names are not allowed.
    AdGroup group3 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
            .setName(group1.getName())
            .build();

    AdGroupOperation op1 = AdGroupOperation.newBuilder().setCreate(group1).build();
    AdGroupOperation op2 = AdGroupOperation.newBuilder().setCreate(group2).build();
    AdGroupOperation op3 = AdGroupOperation.newBuilder().setCreate(group3).build();

    try (AdGroupServiceClient service =
        googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
      // Issues the mutate request, setting partialFailure=true.
      return service.mutateAdGroups(
          String.valueOf(customerId),
          Arrays.asList(op1, op2, op3),
          // Sets partial failure to true.
          true,
          // Sets validate only to false.
          false);
    }
  }

  /** Inspects a response to check for presence of partial failure errors. */
  private boolean checkIfPartialFailureErrorExists(MutateAdGroupsResponse response) {
    return response.hasPartialFailureError();
  }

  /** Displays the result from the mutate operation. */
  private void printResults(MutateAdGroupsResponse response) throws InvalidProtocolBufferException {
    int operationIndex = 0;
    for (MutateAdGroupResult result : response.getResultsList()) {
      if (ErrorUtils.getInstance().isPartialFailureResult(result)) {
        // May throw on this line. Most likely this means the wrong version of the ErrorUtils
        // class has been used.
        for (GoogleAdsError error :
            ErrorUtils.getInstance()
                .getGoogleAdsErrors(operationIndex, response.getPartialFailureError())) {
          System.out.printf("Operation %d failed with error: %s%n", operationIndex, error);
        }
      } else {
        System.out.printf("Operation %d succeeded.%n", operationIndex);
      }
      ++operationIndex;
    }
  }
}
C#
// Copyright 2019 Google LLC
//
// 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.

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V2.Errors;
using Google.Ads.GoogleAds.V2.Resources;
using Google.Ads.GoogleAds.V2.Services;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <summary>
    /// This code example demonstrates how to handle partial failures.
    /// </summary>
    public class HandlePartialFailures : ExampleBase
    {
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            HandlePartialFailures codeExample = new HandlePartialFailures();
            Console.WriteLine(codeExample.Description);
            try
            {
                long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");

                // The Google Ads customer ID for which the call is made.
                long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

                codeExample.Run(new GoogleAdsClient(), customerId, campaignId);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example demonstrates how to handle partial failures.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to which ad groups are added.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            try
            {
                MutateAdGroupsResponse response = CreateAdGroups(client, customerId, campaignId);

                // Checks for existence of any partial failures in the response.
                if (CheckIfPartialFailureErrorExists(response))
                {
                    Console.WriteLine("Partial failures occurred. Details will be shown below.");
                }
                else
                {
                    Console.WriteLine("All operations completed successfully. No partial " +
                        "failures to show.");
                    return;
                }

                // Finds the failed operations by looping through the results.
                PrintResults(response);

                // Display the results.
                if (response.PartialFailureError == null)
                {
                    Console.WriteLine("Partial failures occurred. Details will be shown below.");
                }
                else
                {
                    Console.WriteLine("All operations completed successfully. No partial " +
                        "failures to show.");
                    return;
                }

                // Finds the failed operations by looping through the results.
                PrintResults(response);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }

        /// <summary>
        /// Displays the result from the mutate operation.
        /// </summary>
        /// <param name="response">The mutate response from the Google Ads API server..</param>
        private void PrintResults(MutateAdGroupsResponse response)
        {
            // Finds the failed operations by looping through the results.
            int operationIndex = 0;
            foreach (MutateAdGroupResult result in response.Results)
            {
                // This represents the result of a failed operation.
                if (result.IsEmpty())
                {
                    List<GoogleAdsError> errors =
                        response.PartialFailure.GetErrorsByOperationIndex(operationIndex);
                    foreach (GoogleAdsError error in errors)
                    {
                        Console.WriteLine($"Operation {operationIndex} failed with " +
                            $"error: {error}.");
                    }
                }
                else
                {
                    Console.WriteLine($"Operation {operationIndex} succeeded.",
                        operationIndex);
                }
                operationIndex++;
            }
        }

        /// <summary>
        /// Inspects a response to check for presence of partial failure errors.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <returns>True if there are partial failures, false otherwise.</returns>
        private static bool CheckIfPartialFailureErrorExists(MutateAdGroupsResponse response)
        {
            return response.PartialFailureError == null;
        }

        /// <summary>
        /// Attempts to create 3 ad groups with partial failure enabled. One of the ad groups
        /// will succeed, while the other will fail.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to which ad groups are added.</param>
        /// <returns>The mutate response from the Google Ads server.</returns>
        private static MutateAdGroupsResponse CreateAdGroups(GoogleAdsClient client,
            long customerId, long campaignId)
        {
            // Get the AdGroupServiceClient.
            AdGroupServiceClient adGroupService = client.GetService(Services.V2.AdGroupService);

            string validAdGroupName = "Valid AdGroup: " + ExampleUtilities.GetRandomString();

            AdGroupOperation[] operations = new AdGroupOperation[]
            {
                // This operation will be successful, assuming the campaign specified in
                // campaignId parameter is correct.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, campaignId),
                        Name = validAdGroupName
                    }
                },
                // This operation will fail since we are using campaign ID = 0, which results
                // in an invalid resource name.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, 0),
                        Name = "Broken AdGroup: " + ExampleUtilities.GetRandomString()
                    },
                },
                // This operation will fail since the ad group is using the same name as the ad
                // group from the first operation. Duplicate ad group names are not allowed.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, campaignId),
                        Name = validAdGroupName
                    }
                }
            };

            // Add the ad groups.
            MutateAdGroupsResponse response =
                adGroupService.MutateAdGroups(customerId.ToString(), operations, true, false);
            return response;
        }
    }
}
Python
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# 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
#
#     https://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.
"""This shows how to handle responses that may include partial_failure errors.
"""

from __future__ import absolute_import

import argparse
import six
import sys
import uuid

from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.errors import GoogleAdsException


def main(client, customer_id, campaign_id):
    """Runs the example code, which demonstrates how to handle partial failures.

    The example creates three Ad Groups, two of which intentionally fail in
    order to generate a partial failure error. It also demonstrates how to
    properly identify a partial error and how to log the error messages.

    Args:
        client:  An initialized GoogleAdsClient instance.
        customer_id: A valid customer account ID.
        campaign_id: The ID for a campaign to create Ad Groups under.
    """
    try:
        ad_group_response = create_ad_groups(client, customer_id, campaign_id)
    except GoogleAdsException as ex:
        print('Request with ID "{}" failed with status "{}" and includes the '
              'following errors:'.format(ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "{}".'.format(error.message))

            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: {}'.format(
                        field_path_element.field_name))
        sys.exit(1)
    else:
        print_results(client, ad_group_response)


def create_ad_groups(client, customer_id, campaign_id):
    """Creates three Ad Groups, two of which intentionally generate errors.

    Args:
        client:  An initialized GoogleAdsClient instance.
        customer_id: A valid customer account ID.
        campaign_id: The ID for a campaign to create Ad Groups under.

    Returns: A MutateAdGroupsResponse message instance.
    """
    ad_group_service = client.get_service('AdGroupService', version='v2')
    campaign_service = client.get_service('CampaignService', version='v2')
    resource_name = campaign_service.campaign_path(customer_id, campaign_id)

    invalid_resource_name = campaign_service.campaign_path(customer_id, 0)
    ad_group_operations = []

    # This AdGroup should be created successfully - assuming the campaign in
    # the params exists.
    ad_group_op1 = client.get_type('AdGroupOperation', version='v2')
    ad_group_op1.create.name.value = 'Valid AdGroup: %s' % uuid.uuid4()
    ad_group_op1.create.campaign.value = resource_name
    ad_group_operations.append(ad_group_op1)

    # This AdGroup will always fail - campaign ID 0 in resource names is
    # never valid.
    ad_group_op2 = client.get_type('AdGroupOperation', version='v2')
    ad_group_op2.create.name.value = 'Broken AdGroup: %s' % (uuid.uuid4())
    ad_group_op2.create.campaign.value = invalid_resource_name
    ad_group_operations.append(ad_group_op2)

    # This AdGroup will always fail - duplicate ad group names are not allowed.
    ad_group_op3 = client.get_type('AdGroupOperation', version='v2')
    ad_group_op3.create.name.value = (ad_group_op1.create.name.value)
    ad_group_op3.create.campaign.value = resource_name
    ad_group_operations.append(ad_group_op3)

    # Issue a mutate request, setting partial_failure=True.
    return ad_group_service.mutate_ad_groups(customer_id, ad_group_operations,
                                             partial_failure=True)


def is_partial_failure_error_present(response):
    """Checks whether a response message has a partial failure error.

    In Python the partial_failure_error attr is always present on a response
    message and is represented by a google.rpc.Status message. So we can't
    simply check whether the field is present, we must check that the code is
    non-zero. Error codes are represented by the google.rpc.Code proto Enum:
    https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto

    Args:
        response:  A MutateAdGroupsResponse message instance.

    Returns: A boolean, whether or not the response message has a partial
        failure error.
    """
    partial_failure = getattr(response, 'partial_failure_error', None)
    code = getattr(partial_failure, 'code', None)
    return code != 0


def print_results(client, response):
    """Prints partial failure errors and success messages from a response.

    This function shows how to retrieve partial_failure errors from a response
    message (in the case of this example the message will be of type
    MutateAdGroupsResponse) and how to unpack those errors to GoogleAdsFailure
    instances. It also shows that a response with partial failures may still
    contain successful requests, and that those messages should be parsed
    separately. As an example, a GoogleAdsFailure object from this example will
    be structured similar to:

    error_code {
      range_error: TOO_LOW
    }
    message: "Too low."
    trigger {
      string_value: ""
    }
    location {
      field_path_elements {
        field_name: "operations"
        index {
          value: 1
        }
      }
      field_path_elements {
        field_name: "create"
      }
      field_path_elements {
        field_name: "campaign"
      }
    }

    Args:
        client: an initialized GoogleAdsClient.
        response: a MutateAdGroupsResponse instance.
    """
    # Check for existence of any partial failures in the response.
    if is_partial_failure_error_present(response):
        print('Partial failures occurred. Details will be shown below.\n')
        # Prints the details of the partial failure errors.
        partial_failure = getattr(response, 'partial_failure_error', None)
        # partial_failure_error.details is a repeated field and iterable
        error_details = getattr(partial_failure, 'details', [])

        for error_detail in error_details:
            # Retrieve an instance of the GoogleAdsFailure class from the client
            failure_message = client.get_type('GoogleAdsFailure', version='v2')
            # Parse the string into a GoogleAdsFailure message instance.
            failure_object = failure_message.FromString(error_detail.value)

            for error in failure_object.errors:
                # Construct and print a string that details which element in
                # the above ad_group_operations list failed (by index number)
                # as well as the error message and error code.
                print('A partial failure at index {} occurred.\n'
                      'Error message: {}\nError code: {}'.format(
                          error.location.field_path_elements[0].index.value,
                          error.message, error.error_code))
    else:
        print('All operations completed successfully. No partial failure '
              'to show.')

    # In the list of results, operations from the ad_group_operation list
    # that failed will be represented as empty messages. This loop detects
    # such empty messages and ignores them, while printing information about
    # successful operations.
    for message in response.results:
        # Empty messages will have a byte size of zero.
        if message.ByteSize() == 0:
            continue

        print('Created ad group with resource_name: {}.'.format(
            message.resource_name))


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage()

    parser = argparse.ArgumentParser(
        description='Adds an ad group for specified customer and campaign id.')
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=six.text_type,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-i', '--campaign_id', type=six.text_type,
                        required=True, help='The campaign ID.')
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.campaign_id)
PHP
<?php
/**
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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\Ads\GoogleAds\Examples\ErrorHandling;

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

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V2\GoogleAdsErrors;
use Google\Ads\GoogleAds\Util\V2\PartialFailures;
use Google\Ads\GoogleAds\Util\V2\ResourceNames;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V2\Resources\AdGroup;
use Google\Ads\GoogleAds\V2\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V2\Services\MutateAdGroupsResponse;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/**
 * Shows how to handle partial failures. There are several ways of detecting partial failures. This
 * highlights the top main detection options: empty results and error instances.
 *
 * <p>Access to the detailed error (<code>GoogleAdsFailure</code>) for each error is via a Any
 * proto. Deserializing these to retrieve the error details is may not be immediately obvious at
 * first, this example shows how to convert Any into <code>GoogleAdsFailure</code>.
 *
 * <p>Additionally, this example shows how to produce an error message for a specific failed
 * operation by looking up the failure details in the <code>GoogleAdsFailure</code> object.
 */
class HandlePartialFailure
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

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

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId a campaign ID
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId
    ) {
        $response = self::createAdGroups($googleAdsClient, $customerId, $campaignId);
        self::checkIfPartialFailureErrorExists($response);
        self::printResults($response);
    }

    /**
     * Create ad groups by enabling partial failure mode.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId a campaign ID
     * @return MutateAdGroupsResponse
     */
    private static function createAdGroups(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId
    ) {
        $campaignResourceName =
            new StringValue(['value' => ResourceNames::forCampaign($customerId, $campaignId)]);

        // This ad group should be created successfully - assuming the campaign in the params
        // exists.
        $adGroup1 = new AdGroup([
            'name' => new StringValue(['value' => 'Valid AdGroup #' . uniqid()]),
            'campaign' => $campaignResourceName
        ]);

        // This ad group will always fail - campaign ID 0 in the resource name is never valid.
        $adGroup2 = new AdGroup([
            'name' => new StringValue(['value' => 'Broken AdGroup #' . uniqid()]),
            'campaign' => ResourceNames::forCampaign($customerId, 0)
        ]);

        // This ad group will always fail - duplicate ad group names are not allowed.
        $adGroup3 = new AdGroup([
            'name' => $adGroup1->getName(),
            'campaign' => $campaignResourceName
        ]);

        $operations = [];

        $adGroupOperation1 = new AdGroupOperation();
        $adGroupOperation1->setCreate($adGroup1);
        $operations[] = $adGroupOperation1;

        $adGroupOperation2 = new AdGroupOperation();
        $adGroupOperation2->setCreate($adGroup2);
        $operations[] = $adGroupOperation2;

        $adGroupOperation3 = new AdGroupOperation();
        $adGroupOperation3->setCreate($adGroup3);
        $operations[] = $adGroupOperation3;

        // Issues the mutate request, enabling partial failure mode.
        $adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
        return $adGroupServiceClient->mutateAdGroups(
            $customerId,
            $operations,
            ['partialFailure' => true]
        );
    }

    /**
     * Check if there exists partial failure error in the given mutate ad group response.
     *
     * @param MutateAdGroupsResponse $response the mutate ad group response
     */
    private static function checkIfPartialFailureErrorExists(MutateAdGroupsResponse $response)
    {
        if (!is_null($response->getPartialFailureError())) {
            printf("Partial failures occurred. Details will be shown below.%s", PHP_EOL);
        } else {
            printf(
                "All operations completed successfully. No partial failures to show.%s",
                PHP_EOL
            );
        }
    }

    /**
     * Print results of the given mutate ad group response. For those that are partial failure,
     * print all their errors with corresponding operation indices. For those that succeeded, print
     * the resource names of created ad groups.
     *
     * @param MutateAdGroupsResponse $response the mutate ad group response
     */
    private static function printResults(MutateAdGroupsResponse $response)
    {
        // Finds the failed operations by looping through the results.
        $operationIndex = 0;
        foreach ($response->getResults() as $result) {
            /** @var AdGroup $result */
            if (PartialFailures::isPartialFailure($result)) {
                $errors = GoogleAdsErrors::fromStatus(
                    $operationIndex,
                    $response->getPartialFailureError()
                );
                foreach ($errors as $error) {
                    printf(
                        "Operation %d failed with error: %s%s",
                        $operationIndex,
                        $error->getMessage(),
                        PHP_EOL
                    );
                }
            } else {
                printf(
                    "Operation %d succeeded: ad group with resource name '%s'.%s",
                    $operationIndex,
                    $result->getResourceName(),
                    PHP_EOL
                );
            }
            $operationIndex++;
        }
    }
}

HandlePartialFailure::main();
Ruby
# Encoding: utf-8
#
# Copyright 2019 Google LLC
#
# 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
#
#     https://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.
#
# This code example shows how to deal with partial failures

require 'optparse'
require 'google/ads/google_ads'

def add_keywords(customer_id, ad_group_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  criteria = [
    "mars cruise",
    "inv@lid cruise",
    "venus cruise",
    "b(a)d keyword cruise"
  ].map { |keyword|
    client.resource.ad_group_criterion do |agc|
      agc.ad_group = client.path.ad_group(customer_id, ad_group_id)
      agc.keyword = client.resource.keyword_info do |ki|
        ki.text = keyword
        ki.match_type = :EXACT
      end
    end
  }

  operations = criteria.map { |criterion|
    client.operation.create_resource.ad_group_criterion(criterion)
  }

  criterion_service = client.service.ad_group_criterion
  response = criterion_service.mutate_ad_group_criteria(
    customer_id,
    operations,
    partial_failure: true,
  )

  response.results.each_with_index do |criterion, i|
    if criterion.resource_name != ""
      puts("operations[#{i}] succeeded: Created ad group criterion with id #{criterion.resource_name}")
    end
  end

  failures = client.decode_partial_failure_error(response.partial_failure_error)
  failures.each do |failure|
    failure.errors.each do |error|
      human_readable_error_path = error
        .location
        .field_path_elements
        .map { |location_info|
          if location_info.index
            "#{location_info.field_name}[#{location_info.index}]"
          else
            "#{location_info.field_name}"
          end
        }.join(" > ")

      errmsg =  "error occured creating criterion #{human_readable_error_path}" \
        " with value: #{error.trigger.string_value}" \
        " because #{error.message.downcase}"
      puts errmsg
    end
  end
end

if __FILE__ == $PROGRAM_NAME
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-A', '--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_keywords(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:ad_group_id),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
        e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

Google Ads API Beta
Google Ads API Beta
Need help? Visit our support page.